Home / Learn React / You Might Not Need an Effect
You Might Not Need an Effect
Effects are an escape hatch. A lot of beginner code uses them where plain render logic or an event handler is simpler and faster. Learn the common cases.
Theory in plain words
What it is
This lesson is a checklist for removing unnecessary effects. The question to ask is: why does this code run? Because the component appeared on screen (effect) or because the user did something (event handler)?
Why we use it
Extra effects cause extra renders, flickers, infinite loops and bugs where values are out of sync. Removing them makes code shorter and more reliable.
How it works
Anything computed from existing props or state belongs in the render body. Anything triggered by a user action belongs in a handler. Effects are for syncing with external systems.
Where it is used
- Code reviews of React projects
- Fixing "state is one render behind" bugs
- Cleaning up filtered lists and derived values
Case 1: derived values
The wrong version renders twice for every change. The right version renders once.
Case 2: reset state when a prop changes
Changing key makes React throw the old component away and start a fresh one with empty state. No effect needed.
Case 3: user actions go in handlers
Case 4: expensive calculation
If a calculation is truly slow, wrap it in useMemo (next lessons) instead of an effect that stores the result in state.
- Do not copy props into state just to "keep them in sync" unless you want an editable draft.
- Do not chain effects that set state to trigger other effects.
- Do not notify the parent from an effect after state changed. Call the parent's function in the same event handler.
Quick quiz
1. Filtered list based on props and state. Where should it be calculated?
Derived values should be calculated during rendering.
2. How can you reset a component state when a prop like userId changes, without an effect?
A new key makes React create a fresh instance.
3. Where should code that runs because the user clicked Save go?
Actions caused by events belong in handlers.
Common questions
Filtered list based on props and state. Where should it be calculated?
During render. Derived values should be calculated during rendering.
How can you reset a component state when a prop like userId changes, without an effect?
Give it key={userId}. A new key makes React create a fresh instance.
Where should code that runs because the user clicked Save go?
The event handler. Actions caused by events belong in handlers.