What is useReducer Hook in React

The useReducer hook in React is a built-in hook that allows you to manage state in a more complex and structured way. It is an alternative to useState hook when you have more complex state logic that involves multiple sub-values or when the next state depends on the previous state.

The useReducer hook takes in two arguments: a reducer function and an initial state. The reducer function is responsible for updating the state based on the dispatched actions. It takes in the current state and an action object, and returns the new state.

Here’s an example of how to use the useReducer hook in React:

import React, { useReducer } from 'react';
// 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;
}
};
const Counter = () => {
// Initial state
const initialState = { count: 0 };
// useReducer hook
const [state, dispatch] = useReducer(reducer, initialState);
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, we have a simple counter component that uses the useReducer hook. The initial state is an object with a single property count set to 0. The reducer function handles the state updates based on the dispatched actions. In this case, we have two actions: ‘INCREMENT’ and ‘DECREMENT’, which increment and decrement the count respectively. The state and dispatch function returned by useReducer are used to update and access the state in the component.

By using the useReducer hook, you can manage more complex state logic in a structured and predictable way, especially when the state transitions depend on the previous state or involve multiple sub-values.