React Hooks are newly introduced in React version 16.8.0. Hooks are meant to allow react functional components to work as stateful components. The most commonly used hooks are useState and useEffect hooks. Today we will discuss useReducer hook, which is a more powerful functional hook to replace multiple useState hooks in an efficient and optimize way.
Both useState and useReducer do the same thing i.e. update the current state. In other words, useReducer use the reducer function to change the state immutably when an action for state change is dispatched.
For ex:- (state, action) => newState (Accepts a reducer function of this type)
We use useReducer in scenarios where we have to manage complex state logic and where we need the previous state to update the next state. It is most commonly used in implementing validation in react forms. It will reduce the work in defining multiple states and managing those states by just using a useReducer where we can switch states based on dispatch actions (thereby negating the use of callbacks for deep state updates).
When you want to keep several values in the same state variable, useReducer is a good option. Another one is you want the same flow like dispatch-> reducer flow of redux.
If we get further into useReducer, we will see that this function will accept 3 parameters:
– The function to be executed after the dispatch is called. So, this function use state information and action dispatched to return a new state as follows: (state, action) => newState.
– state initial value i.e the initialState
– a function for state initialization, this function will receive a parameter as a second argument and should return the initialState. Alongwith initialState, it will also return an array with 2 values:
– component’s current state
– dispatch function
Example:
import React, {useReducer} from ‘react’;
const initialize = (startCount) => {
return {count: startCount}
}
const reducerFxn = (state, action) => {
switch(action.type){
case ‘addition’:
return {count: state.count + 1};
case ‘substraction’:
return {count: state.count – 1};
case ‘reset’:
return initialize(action.payload);
default:
throw new Error();
}
}
const Count = ({startCount}) => {
const[state, dispatch] = useReducer(reducerFxn, startCount, initialize);
return(
<>
Count: {state.count}
<button
onClick={() => dispatch({type: ‘reset’, payload: startCount})}>
Reset
</button>
<button onClick={() => dispatch({type: ‘addition’})}> + </button>
<button onClick={() => dispatch({type: ‘substraction’})}> – </button>
</>
);
}
If you want to return the same state out of the reducer function, it will not re-render the children. Although it may render the same component, but it will definitely not go deeper down to child level components.
Conclusion:
– helps developers try to hold several values in the same state variable.
– suits your needs when the next state value depends on the previous one.
Thanks for giving your valuable time. Keep reading and keep learning