Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Reducer | Redux Toolkit
Expert React
course content

Conteúdo do Curso

Expert React

Expert React

1. React Key Concepts
2. React Router
3. Redux Toolkit
4. Formik
5. Jest
6. Next Steps

bookReducer

Step 4: Reducers and their role in state management

Theory

Reducers are pure functions that specify how the state should change in response to dispatched actions. By taking in the current state and an action as parameters, reducers return the new state of the application.

Practice

In our project's reducers folder, we have the counterReducer.js file where we define the reducer for our counter functionality:

Code explanation:

  • Line 1: Import the createReducer function from the @reduxjs/toolkit package. This function is used to create reducers in Redux.
  • Line 2: Import the increment and decrement action creators from the ../actions/counterAction.js file. These action creators are used to define the actions that the reducer will handle.
  • Line 4: Set the initialState constant to 0. This represents the initial value of the counter in the Redux store.
  • Line 6: Use the createReducer function to define the counterReducer.
  • Line 6-11: The createReducer function takes two arguments: the initialState and a callback function that defines how the state should be updated based on dispatched actions.
  • Line 7: Use the builder object to define the cases for different actions inside the callback function.
  • Line 9, 10: Use the addCase method of the builder object to define how the state should be updated when specific actions, such as increment and decrement, are dispatched.
  • Line 9, 10: The callback function inside addCase takes the current state (state) as an argument and returns the new state after applying the corresponding action.
  • In this case, when the increment action is dispatched, the state is incremented by 1; when the decrement action is dispatched, the state is decremented by 1.
  • Line 13: Finally, export the counterReducer as the default export of the module.

Note

To summarize, the counterReducer will handle the dispatched actions and update the counter state accordingly in the Redux store.

Complete code

What is the purpose of reducers in Redux?

What is the purpose of reducers in Redux?

Selecione a resposta correta

Tudo estava claro?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

Seção 3. Capítulo 6
some-alt