Hey coders!!!
In this new post of react, we will check other useful hook...
UseReducer.-
ππ» If you find yourself keeping track of multiple pieces of state that rely on complex logic.
- Manage complex state in react apps
- Works like a state management (Redux, etc).
The basics:
ππ» useReducer(reducer, initialState)
The reducer function contains your custom state logic and the initialState can be a simple value but generally will contain an object.
The useReducer Hook returns the current state and a dispatch method.
ππ» As always the best way to learn is with some code.
The result of this code will be:
We can see the popular count with two buttons, increase and decrease.
1 . Let's begin with a initial state and the reducer function.
const initialState = {count: 0};
const reducer = (state, action) => {
switch (action.type) {
case 'increase':
return { count: state.count + 1 }
case 'decrease':
return { count: state.count - 1 }
default:
return state;
}
}
This portion of code will help in the main app
const [state, dispatch] = useReducer(reducer, initialState);
2 . Create the increaseCount and decreaseCount functions with dispatch:
const increaseCount = () => {
dispatch({ type: 'increase' });
}
const decreaseCount = () => {
dispatch({ type: 'decrease' });
}
3 . Finally the return part:
return (
<>
<h2>Count: {state.count}</h2>
<button onClick={increaseCount}>Increase</button>
<button onClick={decreaseCount}>Decrease</button>
</>
);
We are showing two buttons and after clicked the increaseCount and decreaseCount will be executed.
For task we can add some improvements like create an object for 'increase' and 'decrease' strings.
Here you have the full version of code:
import { useReducer } from "react";
const ACTION = {
INCREASE: "increase",
DECREASE: "decrease",
};
const initialState = { count: 0 };
const reducer = (state, action) => {
switch (action.type) {
case ACTION.INCREASE:
return { count: state.count + 1 };
case ACTION.DECREASE:
return { count: state.count - 1 };
default:
return state;
}
};
export default function App() {
const [state, dispatch] = useReducer(reducer, initialState);
const increaseCount = () => {
dispatch({ type: ACTION.INCREASE });
};
const decreaseCount = () => {
dispatch({ type: ACTION.DECREASE });
};
return (
<>
<h2>Count: {state.count}</h2>
<button onClick={increaseCount}>Increase</button>
<button onClick={decreaseCount}>Decrease</button>
</>
);
}
Conclusion:
We will use useReducer to manage complex states in react applications.
For simple applications we can use useContext or other ways to manage the state.
Let me know if this post is useful for you and also if you want to check in the same the rest of hooks missing.
Have a great day for coding :D
Top comments (0)