Contenido del Curso
Expert React
Expert React
Reducer
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
anddecrement
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 to0
. This represents the initial value of the counter in the Redux store. - Line 6: Use the
createReducer
function to define thecounterReducer
. - Line 6-11: The
createReducer
function takes two arguments: theinitialState
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 thebuilder
object to define how the state should be updated when specific actions, such asincrement
anddecrement
, 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 by1
; when thedecrement
action is dispatched, the state is decremented by1
. - 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
¡Gracias por tus comentarios!