Mastering React’s useReducer Hook: A Simple Guide for Beginners

Bhagya Wijenayake
2 min readJan 24, 2024

--

The useReducer hook is a state management hook in React that is used as an alternative to the useState hook when dealing with more complex state logic. It is particularly useful when the next state depends on the previous one and involves multiple sub-states.

Here’s a basic breakdown of how it works:

1.Reducer Function:

  • The useReducer hook takes two arguments. The first argument is a reducer function, and the second argument is the initial state.
  • The reducer function is responsible for specifying how the state should change in response to certain actions. It takes the current state and an action as parameters and returns the new state.
const reducer = (state, action) => {
// switch statement to handle different actions
switch (action.type) {
case 'INCREMENT':
return { count: state.count + 1 };
case 'DECREMENT':
return { count: state.count - 1 };
default:
return state;
}
};

2.Dispatch Function:

  • The useReducer hook returns an array with two elements: the current state and a dispatch function.
  • The dispatch function is used to trigger state updates. It takes an action object as an argument and passes it to the reducer.
const [state, dispatch] = useReducer(reducer, { count: 0 });

3.Dispatching Actions:

  • To update the state, you call the dispatch function with an action object.
  • The action object typically has a type property that indicates the type of action and may include additional data.
dispatch({ type: 'INCREMENT' });
dispatch({ type: 'DECREMENT' });

4.Updating the UI:

  • You can use the state obtained from useReducer in your components to update the UI.
return (
<div>
Count: {state.count}
<button onClick={() => dispatch({ type: 'INCREMENT' })}>Increment</button>
<button onClick={() => dispatch({ type: 'DECREMENT' })}>Decrement</button>
</div>
);

The useReducer hook is particularly beneficial when you have complex state logic, or when the next state depends on the previous state and multiple actions. It helps to centralize and manage state transitions in a more structured way compared to using multiple useState hooks.

Happy Coding!!!

-Bhagya Wijenayake

--

--

Bhagya Wijenayake

Trainee Software Engineer | React, Angular, Node.js, Next.js | Coding Enthusiast 💻 | Dog Lover 🐾 | Sharing Moments & Stories 📸📖