useReducer hook for multiple states in the React

Today we will show you how to use the useReducer hook for multiple states in the React component. In the previous article, we have taken a simple counter example using useReducer hook.

Here, we will take multiple state object and manage states using a single useReducer hook. The user interface of your demo will look like below.

Output - useReducer hook for multiple states in the React - Clue Mediator
Output – useReducer hook for multiple states in the React – Clue Mediator

useReducer hook for multiple states

  1. Create react application and add useReducer
  2. Use complex state and action
  3. Add second counter
  4. Output

1. Create react application and add useReducer

Let’s create a simple react app by executing the following command.

Now, create a counter example using the useReducer react hook. Refer to the previous article.

You may have noticed that we have taken the counter state directly as an integer type, but in the next step, we will create a multiple counter example using the object type.

2. Use complex state and action

Let’s update the state and reducer method where we will manage the multiple state based on the action.type and the action.value.

In the above code, we have used the Spread Operator to update the individual state value and return the state object.

Let’s update the button click and display value.

3. Add second counter

In this step, we will increase & decrease the counter2 by 10 using the same reducer. For that we have to add a few more action types in the reducer function.

In the above code, we have passed the value as a 10 in the dispatch method to update the counter2.

4. Output

Let’s combine all code together and see how it looks.

App.js

Run the application and check the output in the browser.

That’s it for today.
Thank you for reading. Happy Coding..!! 🙂

Demo & Source Code

Github Repository StackBlitz Project
If you found value in this article,
you can support us by buying me a coffee! ☕

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *