Normally if we have two component with same state and action structure we will make one reducer like this:
Very long and messy. Right?
With useReducer
we can create different instance of state and dispatch for a counter with same reducer.
Remember to import useReducer from react
import React, { useReducer } from “react”;
Now, if we want to have more counter, we do not need to modify any code of the reducer but just add one line of the code:
const [counter3, dispatch3] = useReducer(reducer, init)
Summary
If we have multiple component with same state and action structure, we should build a reducer for one component, then use useReducer to create different instance for each component.