State Management in Pure React with Hooks: useReducer

bipinrajbhar

Bipin Rajbhar

Posted on April 13, 2020

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.

πŸ’– πŸ’ͺ πŸ™… 🚩
bipinrajbhar
Bipin Rajbhar

Posted on April 13, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related