What is the useReducer hook?

useReducer is a hook in React that allows you to manage state within your components. It is similar to useState, but it is more powerful and can be more efficient in certain situations.

useReducer takes two arguments: a reducer function and an initial state. The reducer function is a pure function that takes the current state and an action, and returns the next state. The initial state is the starting value for the state.

Here is an example of how you might use useReducer in a React component:

import { useReducer } from 'react';
function reducer(state, action) {
switch (action.type) {
case 'increment':
return { count: state.count + 1 };
case 'decrement':
return { count: state.count - 1 };
default:
throw new Error();
}
}

function Counter() {
const [state, dispatch] = useReducer(reducer, { count: 0 });

return (
<>
Count: {state.count}
<button onClick={() => dispatch({ type: 'increment' })}>+</button>
<button onClick={() => dispatch({ type: 'decrement' })}>-</button>
</>
);
}

In this example, the Counter the component manages its state using useReducer. The reducer function handles the logic for updating the state based on the dispatched actions. The component uses the dispatch function to send actions to the reducer, which updates the state and re-renders the component with the new state.

useReducer is a powerful tool for managing state in React, and it can be beneficial for managing complex state or state that depends on the previous state. It can also be more efficient than useState in some instances because it allows you to batch updates to the state and avoid unnecessary re-renders.

DCT Academy
Full Stack web development training institute in Bangalore

Launch your GraphyLaunch your Graphy
100K+ creators trust Graphy to teach online
𝕏
Best MERN Full Stack Development Course | Bangalore | Offline | Online | 100% Placements | Training Institute | Front End Course | React JS Training | Online Course India 2024 Privacy policy Terms of use Contact us Refund policy