useReducer in React Hook

Today we will show you how to use useReducer in React Hook. useReducer is a hook that is used for state management in React. The useState is built using the useReducer. So use it when you have a complex state logic that contains multiple sub values.

Syntax

Use the following syntax for useReducer hook.

Generally, the useReducer hook will accept the two parameters such as reducer method and the initial state.

It will return the two arguments in the form of an Array. The first argument of the array will provide the value of the state variable and the second argument will be the dispatch method that is used to update the state.

Example of the useReducer Hook

  1. Create a react application
  2. Design a page in the react component
  3. Use the useReducer hook
  4. Output

In this example, we will create a counter example using the useReducer where we will increment and decrement the count value by clicking on the buttons.

1. Create a react application

Here, we will create a startup react application using create-react-app. Run the following command to create a react app.

2. Design a page in the react component

Let’s design a page in the react component to show the counter value and add the three different buttons called Increment, Decrement, and Reset. On click of the button, we will change the value of the counter.

App.js

3. Use the useReducer hook

Now use the useReducer hook in the example. We will create a separate function to manage the state based on the action that is provided in the argument.

We will use the following function and the state variable.

Let’s use the above function in the react component.

App.js

4. Output

Run the react application and check the output in the browser.

Output - useReducer in React Hook - Clue Mediator
Output – useReducer in React Hook – Clue Mediator

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 *