Effects with useEffect

View saved

Basic effect

Effects run after paint. Use them for work that is not just computing JSX.

import { useEffect, useState } from "react";

function DocumentTitle({ title }) {
  useEffect(() => {
    document.title = title;
  }, [title]);
  return <h1>{title}</h1>;
}

Dependency array

  • Omit dependencies carefully—prefer listing values you read inside the effect
  • Empty array [] means run once after mount
  • Include every reactive value the effect uses
  • Missing deps can cause stale data; extra deps can re-run too often

Cleanup function

Return a function to cancel timers or unsubscribe when the component unmounts or before the effect re-runs.

useEffect(() => {
  const id = setInterval(() => {
    console.log("tick");
  }, 1000);
  return () => clearInterval(id);
}, []);

Do not fetch blindly forever

Fetching belongs in effects, but cancel or ignore stale responses when the query changes—covered next.

Comments

One comment per signed-in account. Comments are saved with this page’s URL.