Alternate ways to manage state in React.

Ishwar Rimal
2 min readSep 16, 2023

--

Apart from using the regular useState hook, you can manage the state using useReducer hook.

The useReducer hook in React is a built-in hook that provides a way to manage and update the state in functional components, especially when the state logic is complex or involves multiple values. It is often used as an alternative to useState when you need to handle more advanced state management scenarios.

Here’s how to use the useReducer hook in a React functional component:

import React, { useReducer } from 'react';

// Define a reducer function
const reducer = (state, action) => {
switch (action.type) {
case 'INCREMENT':
return { count: state.count + 1 };
case 'DECREMENT':
return { count: state.count - 1 };
default:
return state;
}
};

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

return (
<div>
<p>Count: {state.count}</p>
<button onClick={() => dispatch({ type: 'INCREMENT' })}>Increment</button>
<button onClick={() => dispatch({ type: 'DECREMENT' })}>Decrement</button>
</div>
);
}

export default Counter;

In this example:

  1. We define a reducer function that takes the current state and an action as arguments and returns a new state based on the action type. In this case, it handles two actions: 'INCREMENT' and 'DECREMENT'.
  2. In the Counter functional component, we call useReducer and pass the reducer function and an initial state object ({ count: 0 }) as arguments. This hook returns the current state (state) and a dispatch function that allows us to send actions to the reducer.
  3. Inside the component’s JSX, we display the current count from the state and provide buttons to increment and decrement the count. When the buttons are clicked, we call dispatch with the appropriate action type ('INCREMENT' or 'DECREMENT'), which triggers the state update through the reducer.

useReducer is especially useful when your state logic becomes more complex or when you need to manage multiple values in your state. It provides a clear separation of concerns between state updates and state presentation in functional components.

useReducer vs Redux

useReducer is similar to Redux , an external state management library which was used before the introduction of useReducer . Now redux is only recommended for complex management.

Jump here for a detailed comparison.

--

--

Ishwar Rimal

Senior FrontEnd Engineer at Intuit. 8 years experience. I write articles on JavaScript, React, Web Optimisation, Startups, Work Life Balance, etc. ❤️ JavaScrip