useReducer
Learn how to manage complex states in function components.
We'll cover the following
Managing complex states
The useReducer()
Hook is an alternative solution for useState()
and allows us to manage more complex states. It’s based on flux architecture in which a reducer function creates a new state by being passed the last state and an action.
The reducer function is called by executing a dispatch function, that in turn receives an action. The action is an object which always has a type
property and often a payload
property
attached. From this action and the previous state, the reducer function can then create the new state. We can summarize this in the following form:
(oldState, action) => newState
The useReducer()
Hook has the following form:
const [state, dispatch] = useReducer(reducerFunc, initialState, initFunc);
Let’s have a look at a simple example. We have developed a Counter
component that can increment or decrement a counter by pressing a +
and -
button:
Get hands-on with 1200+ tech skills courses.