Skip to main content

Command Palette

Search for a command to run...

React Hooks Part 2 ๐Ÿ˜

๐Ÿ™ Welcome back again ๐Ÿ™

Updated
โ€ข2 min readโ€ขView as Markdown
React Hooks Part 2 ๐Ÿ˜
A
Dedicated and efficient full stack developer with 8+ years of experience in application layers, presentation layers, and databases. Developed multiple web applications as a full stack developer to process, analyze, and render data visually. Worked on query optimization for the betterment of existing sections.

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

More from this blog

D

Dev Station

29 posts

Dedicated and efficient full stack developer with 6+ years of experience in application layers, presentation layers, and databases ๐Ÿ™‚