What is useReducer Hook📎?
The useReducer Hook is similar to the useState Hook.
It allows for custom state logic👩💻.
If you find yourself keeping track of multiple pieces of state that rely on complex logic, useReducer is useful.
Syntax:
The useReducer Hook accepts two arguments.
import {useReducer) from 'react'
useReducer(<reducer>,<initialState>)
The reducer function contains your custom logic and the initialState can be a simple value but generally will contain an object.
The useReducer method returns the current state and a dispatch method.
Example😁:
import React, { useReducer } from 'react';function Counter() {
// First render will create the state, and it will
// persist through future renders
const [sum, dispatch] = useReducer((state, action) => {
return state + action;
}, 0);return (
<>
{sum}<button onClick={() => dispatch(1)}>
Add 1
</button>
</>
);
}
In the next article I will be writing about useCallback Hook🤔 ?
That’s all for Today, Stay Tuned and I will see you in the next one👋🏻.
Thanks for Following and Claps😋
Link to Day 15