Introduction to Redux Actions and Reducers
Redux is a state management library commonly used in React applications. It helps in managing the application state in a predictable way. Redux actions and reducers are two fundamental concepts in Redux.
Redux Actions
Actions in Redux are plain JavaScript objects that represent an intention to change the state. They describe what happened in the application and include information necessary for the state change. Actions have a type
property that specifies the type of action being performed.
Here's an example of a Redux action that updates a user's name:
1const updateUser = (name) => {
2 return {
3 type: 'UPDATE_USER',
4 payload: name
5 };
6};
In the above example, the UPDATE_USER
action is defined with a payload
property that contains the new name.
Redux Reducers
Reducers are pure functions in Redux that specify how the application's state should change in response to actions. A reducer takes the current state and an action as arguments and returns the new state.
Here's an example of a Redux reducer that handles the UPDATE_USER
action:
1const initialState = {
2 user: {
3 name: ''
4 }
5};
6
7const userReducer = (state = initialState, action) => {
8 switch (action.type) {
9 case 'UPDATE_USER':
10 return {
11 ...state,
12 user: {
13 name: action.payload
14 }
15 };
16 default:
17 return state;
18 }
19};
In the above example, the user
reducer handles the UPDATE_USER
action by updating the name
property of the user object in the state.
Redux actions and reducers work together to manage the state of a Redux application. Actions represent the intention to change the state, while reducers implement the logic to update the state based on the actions.
Understanding Redux actions and reducers is crucial for developing applications using Redux. In the next sections, we'll dive deeper into how to define actions and implement reducers in Redux.