Fullstack CourseLearn by building

react · source-driven

Synchronizing with Effects

Effects let you synchronize a component with an external system (network, DOM, timer). They run after render — they are not the place for ordinary transform logic.

You will learn

  • What Effects are for (external systems)
  • How the dependency array controls re-runs
  • How cleanup functions cancel subscriptions / in-flight work

Effects synchronize — they don’t “load data” as a lifestyle

From the React docs: you don’t need Effects to transform data for rendering, or to handle user events. You need Effects to step outside React — talk to the browser, a third-party widget, or the network.

useEffect(() => {
  // synchronize with something outside React
  const id = setInterval(() => { /* ... */ }, 1000);
  return () => clearInterval(id); // cleanup
}, []);

Dependencies and cleanup

Empty deps ([]) → run after mount (and clean up on unmount). Missing deps → stale values. Cleanup → avoid setting state after unmount / clear timers.

Timer (external system) + health fetch (teaching only)

Timer seconds: 0

Health status: idle

Recap

  • Effects sync with external systems after paint
  • Declare dependencies explicitly
  • Return a cleanup function when you subscribe or fetch
  • Product Nest data → later: Query, not ad-hoc Effect fetch

Challenge

Try this

Add a checkbox “Watch health”. Only run the fetch Effect when watching is true (enabled pattern — preview of Query’s enabled option).