Hey, this article is to explain the hook, useReducer, where it all began, and where it flows into. What is Reduce function?
The story starts from a small simple countryside function called .reduce()
๐. The reduce()
method takes two arguments:
- a callback function, which is often referred to as a reducer.
an optional initial value.
The
reduce()
method executes a callback function "reducer" given by the user on each element of the array.
The callback function accepts four parameters:
- previousValue/ accumulator.
- currentValue.
- currentIndex(optional).
- array(optional);
For example:
let example = arr.reduce(function(accumulator, currentValue, currentIndex, array){
return accumulator+currentValue;
})
Now useReducer..... It is a hook for state management, it accepts a reducer function and the initial state as arguments and it returns an array of 2 items, the current state, and the dispatch function. It is preferable to useState when we have a complex state logic that involves multiple sub-values, or when the next state depends on the previous one. For example:
const initialState = {count: 0};
function reducer(state, action) {
switch (action.type) {
case 'increment':
return {count: state.count + 1};
case 'decrement':
return {count: state.count - 1};
default:
throw new Error();
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<>
Count: {state.count}
<button onClick={() => dispatch({type: 'decrement'})}>-</button>
<button onClick={() => dispatch({type: 'increment'})}>+</button>
</>
);
}
initalState
: The initial state is the value the state is initialized with.action
: it is an object that describes how to update the state.dispatch
: it is a unique function that dispatches an action object.reducer
: reducer function has been explained above.
The Flow:
The dispatch function is called with the action object when an event is triggered or after completing a fetch request. React redirects the action object and the current state value to the reducer function. The reducer function then does the state update using the action object, and it returns a new state. If the state has been updated react re-renders the component.
useReducer
is to be used for complex state updates (at least 2-3 update actions). These concepts further flow into Redux logic and understanding. I will edit this article again and include the redux explanation.