Table of contents
No headings in the article.
This is the 2nd article of React Hooks, where weโre learning about different hooks used in React, and today will learn useReducer hook. Before we get started, I'd recommend reading the last blog of this series React Hooks. Though this hook is entirely independent of we can read and learn it without any prior knowledge of hooks, it would be beneficial to have some basic understanding of the hooks. ๐
Letโs learn about useReducer hook๐
The useReducer hook is similar to useState, but gives us a more structured approach for updating complex values.
We typically use useReducer when our state has multiple sub-values, e.g. an object containing keys that we want to update independently.
The useReducer hook requires 2 arguments, and has an optional 3rd argument:
reducer - a pure function that takes a state and an action, and returns a new state value based on the action.
initialState - any initial state value, just like useState
initializer (optional) - this is optional
The useReducer hook returns the current state, and a dispatch function to update the state.
E.g. const [state, dispatch] = useReducer(reducer, initialState)
Example
Dispatch
The dispatch function takes an action and calls the reducer to update the state.
In the example above, the initial state is 0. When we click on add button, dispatch is called with the action โaddโ as its argument. This argument gets passed to the reducer as action. Then the reducer follows the switch case logic and returns the new state. The same goes with the action โsubtractโ. And reset will set the state back to โ0โ again.
Awesome! itโs so easy right.๐
Thank you ๐
Do checkout useState hook ๐