Open In App

Purpose of useReducer hook in React

The useReducer hook is a state management hook in React that provides an alternative to the useState hook. It is used when the state of a component is complex and requires more than one state variable.

Syntax:

const [state, dispatch] = useReducer(reducer, initialState, init)

Steps to Create React Application :

Step 1: Create a React application using the following command:



npx create-react-app foldername

Step 2: After creating your project folder i.e. foldername, move to it using the following command:

cd foldername

Step 3: After setting up react environment on your system, we can start by creating an App.js file and create a directory by the name of components in which we will write our desired function.



Project Structure:

The updated dependencies in package.json file will look like.

  "dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4",
}

Example: In this example, the reducer function takes two arguments:




import React, { useReducer } from "react";
import "./App.css";
const initialState = 0;
 
const reducer = (state, action) => {
    switch (action) {
        case "add":
            return state + 1;
        case "subtract":
            return state - 1;
        case "reset":
            return 0;
        default:
            throw new Error("Unexpected action");
    }
};
 
const Count = () => {
    const [count, dispatch] = useReducer(reducer, initialState);
 
    return (
        <div className="mainDiv">
            <h2>{count}</h2>
            <div className="btn">
                <button onClick={() => dispatch("add")}>Add</button>
                <button onClick={() => dispatch("subtract")}>Sub</button>
                <button onClick={() => dispatch("reset")}>Reset</button>
            </div>
        </div>
    );
};
 
export default Count;




#root {
    max-width: 1280px;
    margin: 0 auto;
    padding: 2rem;
    text-align: center;
}
 
.mainDiv {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
}
 
.btn {
    margin-top: 20px;
}
 
button {
    margin: 5px;
}

Output:

Output


Article Tags :