React Hooks Part 2 ๐Ÿ˜

React Hooks Part 2 ๐Ÿ˜

๐Ÿ™ Welcome back again ๐Ÿ™

ยท

2 min read

Table of contents

No heading

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๐Ÿ™‚

react-hooks.png

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

react-hooks-code.png

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 ๐Ÿ™‚

Did you find this article valuable?

Support Dev Station by becoming a sponsor. Any amount is appreciated!

ย