React Best Practices

Chapter 3 of 8 · 4 practices · 3 min · 4-question quiz

Effects, and when you do not need one

Effects are an escape hatch for syncing with systems outside React. This chapter shows when to use one and the common cases where you should not.

Start: Use an effect only to sync with something outside React

4 practices in this chapter

  1. 1Use an effect only to sync with something outside ReactAn effect is an escape hatch for connecting to an external system: a browser API, a WebSocket, a third-party widget, a timer. It is not for transforming data for rendering or for reacting to a button…
  2. 2Return a cleanup from every effect that subscribes or starts workIf an effect connects, subscribes, adds a listener or starts a timer, it must undo that in its cleanup function. Without cleanup you: leak listeners; keep sockets open after the component is gone…
  3. 3Keep dependency arrays honest and use useEffectEvent for non-reactive logicEvery reactive value an effect reads must be in its dependency array. Leaving one out to stop the effect from re-running causes stale values and bugs that are hard to trace. Let the…
  4. 4Fetch data through your framework, or guard effect fetches against racesFetching in an effect has well known problems: waterfalls, no caching, no server rendering, and race conditions where an older response arrives last and overwrites newer results.

Check yourself on this chapter

4 questions, right here once you are signed in. Your progress is saved as you read.

Sign up for the quiz