Introduction
With the introduction of hooks in react, a new way of writing and thinking about components has been introduced. One of the most popular hooks is useReducer which helps in the manipulation and handling of state of react components. We will be learning about useReducer in detail through this article.
In react, there are two hooks to handle the state of components, namely
1.useState
2.useReducer
You might be familiar with the useState hook in react, if not, then you can read out this blog for better understanding.
The useReducer is a better alternative to useState as it is easy to handle complex states in useReducer.
But before getting into details, let's see what useReducer is.
useReducer
useReducer is used to store and update the states. It is used for state manipulation and complex state transitions. Just like other hooks in react, it can be imported by the use of the following snippet.
import { useReducer } from "react"; |
The useReducer takes three arguments: reducer, initial state, and function to load the initial state.
Syntax:
Const [state, dispatch]= useReducer(reducer,initialState,init) |
Let’s discuss each argument in the syntax in detail:
Reducer
This is a function that tells what the state should contain depending upon the action taken. It returns an object that is used to update the state. It takes two arguments which are state and action. The action is like an instruction you pass to the reducer function. Based on the action specified, the reducer function executes the necessary state update.
Initial State
The second argument passed is initial State . It represents the default state of the component. Note that if you don’t pass the third argument to useReducer which for initializing the initial state, it will take the second argument as the initial state. The third argument is optional.
Creating the initial state lazily
Lazy initialization is a tactic used in programming to delay the creation of an object or a complex calculation until the first time it is needed.
We already know, useReducer can accept three parameters, but the third parameter is an optional parameter. init function for creating the initial state lazily is optional which lets you extract logic for calculating the initial state outside of the reducer function
The dispatch method
The dispatch function accepts an object representing the type of action we want to execute when called. It sends the kind of action to the reducer function to perform its job, which, of course, is updating the state.
Now we have discussed the useReducer in detail. Let's implement an application to understand it better.