// 🔴 Avoid: Adjusting state on prop change in an Effect
useEffect(() => {
setSelection(null);
}, [items]);
I understand the technical reasons for discouraging useEffect, but it seems like the authors haven't considered this from a readability perspective.
The docs suggest this instead, which is way less concise, declarative, and IMO much less readable:
// Better: Adjust the state while rendering
const [prevItems, setPrevItems] = useState(items);
if (items !== prevItems) {
setPrevItems(items);
setSelection(null);
}
To have the better readability, I would use this custom hook in userland. Since it's so easy for people to abuse useEffect, I would argue React should provide something like the following as a builtin. But if not, the docs should at least recommend it:
Summary
You Might Not Need an Effect has this example:
I understand the technical reasons for discouraging
useEffect
, but it seems like the authors haven't considered this from a readability perspective.The docs suggest this instead, which is way less concise, declarative, and IMO much less readable:
Page
https://react.dev/learn/you-might-not-need-an-effect#adjusting-some-state-when-a-prop-changes
Details
To have the better readability, I would use this custom hook in userland. Since it's so easy for people to abuse
useEffect
, I would argue React should provide something like the following as a builtin. But if not, the docs should at least recommend it: