DEV Community

Cover image for State Management in Pure React with Hooks: useReducer
Bipin Rajbhar
Bipin Rajbhar

Posted on

State Management in Pure React with Hooks: useReducer

Hello, everyone 👋, I hope you are doing great 😊.

So, today you are going to learn all the fundamental concepts of useReducer() Hook in this article.

Before you start, there are some rules you need to follow to use Hooks 😟. Thankfully the React Team has provided an ESLint Plugin called eslint-plugin-react-hooks that help you enforce these rules when using Hooks 🤩.

useReducer Hook

The useReducer() Hook allows you to have a state in the functional component. It is an alternative to useState() Hook.

The useState() Hook is implemented using useReducer() Hook. It means that useReducer() is primitive, and you can use it for everything that you can do with useState().

The useReducer() Hook is preferred over useState() when you have complex state logic that involves multiple sub value or when the next state depends on the previous state.

The useReducer() Hook takes two arguments. The first argument is the reducer() method, and the second argument is the initial state.

The useReducer() returns an array. The first element of an array is the variable that stores the current state, and the second element of an array is a dispatch() method that calls the reducer() method.

Note: React guarantees that the method return by useReducer() have the same memory address and would not change on re-renders.

Reducer Method

The reducer() method takes two arguments. The first argument is the current state, and the second argument is an action. Based on the action, the reducer() method performs some operation and return a new state.

Example

In the example above, when you add or remove a task, every component on the page is re-render, which we will fix in the next article.

Now, you have learned all the fundamental concepts of useReducer() Hook 🤘.

Thanks for reading! My name is Bipin Rajbhar; I love helping people to learn new skills 😊. You can follow me on Twitter if you’d like to be notified about new articles and resources.

Top comments (4)

Collapse
 
bravemaster619 profile image
bravemaster619

I'm used to react-redux. Today I've used react-redux for my react project. The problem is, I've used react-redux for react classes but recently I migrated to react hooks. And the new project is using react hooks. Should I use useReducer for react hooks?

Collapse
 
bipinrajbhar profile image
Bipin Rajbhar

The useReducer is actually a React Hook. It's a part of React API.

The useReducer Hook does 80% of Things what Rudex Does.

I will suggest you use Both.

For more info: medium.com/javascript-scene/do-rea...

Collapse
 
cryptoquick profile image
Distributed Hunter Trujillo

Very good article! You made one spelling error, though. In the title. At least it's a homonym!

Collapse
 
bipinrajbhar profile image
Bipin Rajbhar

thanks 😅