single reducer and multiple useReducer with counter example

Frankie
1 min readApr 21, 2020

--

Photo by Roman Synkevych on Unsplash

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.

--

--

Frankie
Frankie

Written by Frankie

Hi, I am interested in IT field including front-end, back-end, database, networking.

No responses yet