React Hooks Recipes/Polling with effect cleanup

Periodically refresh data until unmount.

Section: Network and Server Recipes

Polling with effect cleanup

tsx
tsx
useEffect(() => {
  let stopped = false;
  async function load() {
    const data = await fetch('/api/status').then(r => r.json());
    if (!stopped) setStatus(data);
  }
  load();
  const id = setInterval(load, 5000);
  return () => {
    stopped = true;
    clearInterval(id);
  };
}, []);
Explanation

Polling needs cleanup and race awareness.

Learn the surrounding workflow

Compare similar commands or jump into common fixes when this command is part of a bigger troubleshooting path.

Related commands

Same sheet · prioritizing Network and Server Recipes
Optimistic UI with transition
Apply urgent optimistic state and schedule reconciliation.
OpenIn sheettsxsame section
Build an interval counter
Update state on an interval with cleanup.
OpenIn sheettsx3 tag match
Mirror a prop into state only when necessary
Initialize from props, then manage locally.
OpenIn sheettsx3 tag match
Focus an input on mount
Use a ref and an effect to focus an input after mount.
OpenIn sheettsx2 tag match
Measure an element’s size
Use a ref plus ResizeObserver.
OpenIn sheettsx2 tag match