24
loading...
This website collects cookies to deliver better user experience
useState
hook and helps in managing complex state logic that involves multiple sub-values or when the next state depends on the previous one. When combined with useContext
and other hooks, it can be a good alternative to redux.useReducer
also lets you optimize performance for components that trigger deep updates because you can pass dispatch down instead of callbacks.import {useReducer} from 'react';
useState
hook, useReducer
hook also returns two things in an Array : the current state value and a dispatch
function to which you can pass an action and invoke later.const [state, dispatch] = useReducer(reducer, initialState)
useReducer
takes two parameters. The first one is the reducer function and second is the initialState. reduce()
method in JavaScript.let array = [1, 2, 3];
let reducer = (total, number) => {
return total + number;
}
let sum = array.reduce(reducer, 0);
console.log(sum) // 6
useReducer
is also similar.const initialState = { count: 0 }
// The reducer function
function countReducer(state, action) {
switch (action.type) {
case 'INCREMENT':
return { count: state.count + 1 }
case 'DECREMENT':
return { count: state.count - 1 }
case 'RESET':
return {count: state.count = 0}
default:
return { count: state.count }
}
}
Switch
Statement and based on the value of action.type
we perform the corresponding operation on the state.dispatch
function.export function Counter() {
const [state, dispatch] = useReducer(countReducer, initialState)
return (
<div>
Count: {state.count}
<button onClick={() => dispatch({ type: 'INCREMENT'})}>+</button>
<button onClick={() => dispatch({ type: 'DECREMENT'})}>-</button>
<button onClick={() => dispatch({ type: 'RESET'})}>Reset</button>
</div>
);
};
dispatch
function, the current state is automatically passed as the first argument. Therefore, we only pass the action object, which has the type of action we want to perform on the state.useReducer
with useContext
for global state management.