What is Redux?
Redux is a library for managing state in JavaScript applications. It helps create applications that behave predictably, are easy to test and work in various environments.
Core Redux Concepts
Store
- Single source of truth for entire application state
- Created using
createStorefunction - Provides methods to access state and update it
Actions
- Simple JavaScript objects describing what happened
- Must have
typeproperty - Can contain additional data
const action = {
type: 'ADD_TODO',
payload: 'Learn Redux'
};
Reducers
- Pure functions that take current state and action
- Return new state
- Never mutate existing state
const todoReducer = (state = [], action) => {
switch (action.type) {
case 'ADD_TODO':
return [...state, action.payload];
default:
return state;
}
};
Redux Principles
-
Single source of truth
- All application state is stored in one object inside one store
-
State is read-only
- Only way to change state is to dispatch action
- All changes happen centrally and in strict order
-
Changes are made with pure functions
- Reducers are pure functions
- They take previous state and action, return next state
Redux Usage Example
// Action Creator
const addTodo = (text) => ({
type: 'ADD_TODO',
payload: text
});
// Reducer
const todoReducer = (state = [], action) => {
switch (action.type) {
case 'ADD_TODO':
return [...state, action.payload];
default:
return state;
}
};
// Store
const store = createStore(todoReducer);
// Subscribe to changes
store.subscribe(() => console.log(store.getState()));
// Dispatch action
store.dispatch(addTodo('Learn Redux'));
When to Use Redux?
Redux should be used when:
- You have complex application state
- State updates frequently
- State update logic is complex
- Application has medium or large codebase
- Many developers work on project
Important to remember:
Redux adds additional complexity to application. For small projects built-in React state management may be sufficient.