DEV Community

Prateek Agrawal
Prateek Agrawal

Posted on

Benefits of using useReducer() over useState() in React.js applications

Cover

In React.js (a popular open-source front-end JavaScript library for building user interfaces) we use useState() and useReducer() to manage the state of our components. While useState() it’s easy to understand and use. But useReducer() is more suitable in complex state management scenarios.

What is useReducer()?

useReducer() is a hook that allows us to manage the state of our components using a reducer function. A reducer is a pure function that takes the current state and an action, and returns a new state. The new state replaces the old state, causing the component to re-render.


Example Code: Increment / Decrement the count using useReducer()

import React, { useReducer } from "react";
function reducer(state, action) {
switch (action.type) {
case "ADD":
return { count: state.count + 1 };
case "SUBTRACT":
return { count: state.count - 1 };
default:
return state;
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, { count: 0 });
return (
<>
Count: {state.count}
<button onClick={() => dispatch({ type: "ADD" })}>Add</button>
<button onClick={() => dispatch({ type: "SUBTRACT" })}>Substract</button>
</>
);
}
Enter fullscreen mode Exit fullscreen mode

Output

Output


Benefits of using useReducer() over useState() :

  1. Better complex state management: When the state becomes complex, it can be difficult to manage using only useState(). useReducer() is better suited for complex state management as it allows us to break down the state into smaller pieces and manage them separately.

  2. Centralized state management: With useReducer(), we can centralize the management of our state, making it easier to debug and understand.

  3. Better scalability: As our application grows, we may need to add more and more states to our components. useReducer() makes it easier to manage and maintain the state as our application grows.

  4. Improved performance: useReducer() performs optimally when compared to useState() because it batches updates to the state. This means that multiple updates to the state can be combined into a single update, improving the overall performance of our application.

  5. Ability to manage multiple states: useReducer() allows us to manage multiple pieces of state using a single reducer function. This can simplify our code and make it easier to maintain.

  6. Better code reuse: useReducer() allows us to extract logic from the components into a separate reducer function. This makes it easier to reuse the same logic in multiple components.

In summary, useReducer() is a powerful hook that provides a more scalable, performant, and flexible way to manage the state in our React JS applications.

Top comments (0)