Problem: You want to reset React state when a component’s props change


Problem: You want to reset React state when a component’s props change.

Solution: Change the component’s key when the props change.

When the key changes, React deletes the old component. It creates a new instance that uses the default state.

No useEffect required. 😎

Two more points:

1. Why not use useEffect? Because resetting state via useEffect is error prone. As new state is added, someone may forget to update the useEffect call.

2. Warning: If the component tree is expensive to render, consider resetting state via useEffect instead.
Problem: "I don't like setting the key in the parent. It's not discoverable, has to be implemented in each usage, and breaks "encapsulation".

Solution: Wrap the component so it manages its own key. Do this in the component's file, and only export the wrapper. Problem solved.

View original on X