Refactoring to `useReducer`
Let’s modify our custom hook to use `useReducer` instead of `useState`.
We'll cover the following...
Refactoring to useReducer
The most intuitive way to make the state reducer pattern work is using the useReducer
hook to manage the internal state.
First, let’s refactor our custom hook to use useReducer
instead of useState
.
To refactor our custom hook to use the useReducer
hook for state updates, everything within the custom hook stays the same except how the expanded
state is managed.
Here’s what’s to be changed.
First, we’ll change the state from just a boolean value, true
or false
, to an object like this: {expanded: true || false}
.
Press + to interact
// useExpanded.jsexport default function useExpanded (initialExpanded = false) {const initialState = { expanded: initialExpanded }...}
Once we do that, we’ll invoke useReducer
to manage the state.
Press + to interact
// useExpanded.js// before...const [expanded, setExpanded] = useState(initialExpanded)// nowconst [{ expanded }, setExpanded] = useReducer(internalReducer, initialState)...
Note how we need to destructure expanded
from the state object in the new implementation on ...
Access this course and 1400+ top-rated courses and projects.