You probably do not need this effect
Five patterns that look like they need an effect, all of which have a better home. Between them they account for most of the effects in most codebases.
Transforming data for rendering: compute it during render. Resetting state when a prop changes: use a key and let the component remount. Reacting to a user action: put it in the event handler, where you have the event and the intent. Notifying a parent of a change: call the callback in the handler that caused it, not in an effect that watches the result. Initialising something once: do it outside the component or lazily in a ref.
The cost of getting this wrong is not only aesthetic. An effect that sets state runs after the browser has painted, so the user sees the intermediate state for a frame, and you have paid for two renders. Chain three of those and you have a visible cascade of flashes on every interaction, which is the characteristic feel of an application built entirely out of effects.
The clarifying question when you are unsure: what caused this? If a specific user action caused it, the handler is the right place, because that is where the cause is known. If it is true whenever these values are true, an effect might be right, but check whether it is true because of a derivation first.
You should now be able to
- Replace an effect with a derivation, an event handler or a key
- Explain the extra render an unnecessary effect costs
Loading…