UseReducer is an alternative to useState. It works better when you have complex state logic that involves multiple sub-values (e.g. if your state is multidimensional object) or when the next state depends on the previous one. UseReducer hook accepts a reducer of type (state, action) => newState, and returns the current state paired with a dispatch method:
Lets see it on example. We have counter, which shows numbers starting from 0 (our initial state), and two buttons: +1 and -1. When we click +1 button, counter number changes its value and color to green, when we click -1 button, counter number changes its value and color to red. Initial color of counter is gray, and counter get this color, when we click third button, named reset, which also resets counter to 0.
And our state is an object, with two values: count and color:
const initState = {count: 0, color: "gray"}
// state - Declaring new state variable, called "counter" and initial count state
const [counter, setCounter] = useReducer(switchOption, initState);
Now we want to write switchOption function, which changes our state depends on action (button that we clicked):
I write code that (usually) works. I tame WordPress, learn React, explore the world of DevOps, and click around in the Linux console. I optimize code as a hobby, because laziness is the purest form of productivity. I do my best not to lose my mind somewhere between a bug and a deadline.