Multiple useReducer Hook in React
In this article, we will show you how to use the multiple useReducer Hook in React. In the previous two articles, we learned about the use of the useReducer.
Today we will take a counter example from the previous article and use the useReducer for multiple purposes. We’ll create the following user interface for demo.
Output - Multiple useReducer Hook in React - Clue Mediator
Use multiple useReducer Hook in React
1. Create a react application
Let’s create a startup react application using the `create-react-app` package. Run the following command to create a react app.
npx create-react-app multiple-usereducer-hook
2. Implement counter example
We have to implement the simple counter example using the useReducer Hook. Refer to the following link for the implementation.
Example of the useReducer Hook
3. Use multiple useReducer
In this step, we will use the same reducer function for multiple counters. We don’t need to initialize the different states for the second counter. All useReducer hooks will behave as individual states.
In the following code, we have added another counter using the same reducer function and initial state.
App.js
import React, { useReducer } from "react";
const initialState = 0;
const reducer = (state, action) => {
switch (action) {
case 'increment':
return state + 1;
case 'decrement':
return state - 1;
case 'reset':
return initialState;
default:
return state;
}
}
function App() {
const [count, dispatch] = useReducer(reducer, initialState);
const [count2, dispatch2] = useReducer(reducer, initialState);
return (
<div class="App">
<h3>Multiple useReducer hook - <a href="https://www.cluemediator.com" target="_blank" rel="noopener noreferrer">Clue Mediator</a></h3>
<span>First Counter: {count}</span>
<button onclick="{()" ==""> dispatch('increment')}>Increment</button>
<button onclick="{()" ==""> dispatch('decrement')}>Decrement</button>
<button onclick="{()" ==""> dispatch('reset')}>Reset</button>
<br><br>
<span>Second Counter: {count2}</span>
<button onclick="{()" ==""> dispatch2('increment')}>Increment</button>
<button onclick="{()" ==""> dispatch2('decrement')}>Decrement</button>
<button onclick="{()" ==""> dispatch2('reset')}>Reset</button>
</div>
);
}
export default App;
4. Output
Run the react app and check the output in the browser.
That’s it for today.
Thank you for reading. Happy Coding..!! 🙂