Member-only story
Updating State From Properties With React Hooks
And why you shouldn’t change state from useEffect dependencies

How many times have we wanted to update a component’s internal state with data from its properties? There are a variety of ways to do it, but some come with pitfalls.
The Problem: Props Don’t Always Cut It
React is opinionated about not updating state to reflect prop changes, and with good reason. It gets much more challenging and complex to keep track of what the state should reflect. This is the idea behind controlled components, where the controlled component updates the parent’s state instead of trying to synchronize the two components.
The problem with fully controlled components is that, sometimes, the state inside the component can get quite complex. The parent may only care about, say, listing the end result of a search against a server’s database. Ideally, we would have the search results appear in a global state store such as Redux or context, and the state would simply trickle down where it’s needed in our application. But sometimes — especially with a reusable component — it would be nice to be able to encapsulate the search component, read the value
to search on, and return the results by calling an onSearch
property.
This is why so many of us end up using state in a component that needs to track changes in the properties being received.
Let’s look at some of the ways we can update state from properties in functional components, their pros and cons, followed by my preferred approach.
Using useEffect: Please Don’t
How often have we seen something like this?
It looks like a simple and elegant approach. Whenever externalState
changes, the effect fires, updating internalState
. Three lines, and done.
Except it’s incredibly expensive.