How to use useReducer Hook in React
The useReducer Hook is the better alternative to the useState hook.useReducer helps you manage complex state logic in React. For Example You are creating a counter react app in which you implemented three functionality like increment, descrement and reset. So you can use useState but you can implement useReducer Hook to perform that operation.
The useReducer hook accept 2 arguments: the reducer function and the initial state. The hook then returns an array of 2 items: the current state and the dispatch function.
const [state, dispatch] = useReducer(reducer, initialState);
The reducer is a pure function that accepts 2 parameters: the current state and an action object.
const reducer = (state, action) => { switch (action.type) { case "inc": { return state + 1; } case "dec": { return state - 1; } default: throw new Error(); } };
The click event handlers of the INCREMENT, DECREMENT buttons correspondingly use the dispatch() function to dispatch the necessary action object.
<button onClick={() => dispatch({ type: "inc" })}>INC</button> <button onClick={() => dispatch({ type: "dec" })}>INC</button>
#Program to demonstrate the use of useReducer Hook
import "./styles.css"; import { useReducer } from "react"; export default function App() { const reducer = (state, action) => { switch (action.type) { case "inc": { return state + 1; } case "dec": { return state - 1; } default: throw new Error(); } }; const initialState = 0; const [state, dispatch] = useReducer(reducer, initialState); return ( <div className="App"> <h1>Count {state}</h1> <button onClick={() => dispatch({ type: "inc" })}>INC</button> <button onClick={() => dispatch({ type: "dec" })}>DEC</button> </div> ); }