React · Lesson 42 of 120
You Might Not Need an Effect
Simpler code.
Effects are for reaching outside React. A common mistake is using them for things that aren't side effects at all. That makes code slower, and harder to follow.
- Effects reach outside
- Often misused
- Slower code
Filtering a list
On the left, an effect copies a filtered list into extra state, after every change. That's an extra render, and extra state to keep in sync. On the right, we just calculate it while rendering. Simpler, and always correct.
Effect
- const [shown, setShown] = useState([])useEffect(() => setShown(...), [q])Extra render
Calculate
- const shown = items.filter(...)No effectAlways right
Use an effect?
Calculating from props or state, no. Calculate it while rendering. Responding to a click, no. Do it in the event handler. Talking to the outside world, yes. That's what effects are for.
| Task | Where |
|---|---|
| Calculate from state | during render |
| Respond to a click | event handler |
| Sync with outside | useEffect |
Summary
Only use effects to sync with the outside world. Calculate during render, and handle events in handlers. Next, use ref.
Key takeaways- Calculate
- Handlers
- Effects for outside
Next up: useRef — values that don't re-render