AI Hints
Home›React Tutorial›Fetching Data
React · Lesson 42 of 120

You Might Not Need an Effect

Simpler code.

⏱ 2 min read▶ Video at 33:38🎓 Free
Watch this lesson in the React courseWatch on YouTube ↗Full React course

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.

TaskWhere
Calculate from stateduring render
Respond to a clickevent handler
Sync with outsideuseEffect

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