How can I run some code after changing state with React hooks?
Running some code after changing state is a common desire. Let’s look at how to do that with hooks.
Method 1 — useEffect hook
The first and most commonly used method to run a function after updating state is the useEffect
hook. useEffect
runs its function only when the items in the dependency array change. Sounds pretty spot on for what we want huh? Let’s see it in action:
Pretty simple, every time name
changes, we’ll run the function, which console.log
s the name out.
Method 2 — useReducer hook
When you find yourself needing more complex state updates, where updating one item of state affects another item of state, you can reach for useReducer
.
What if we had a status, and wanted to save a history of the last 10 statuses? Because the history relies on changes to the status, useReducer
would be a good choice here. Let’s see it in action:
tl;dr — if the state (and code to run) is simple, you can go with useEffect
. If you’ve got multiple items of state that need to be updated based on changes, go with useReducer
.
Originally published at https://chriscolborne.com.