useEffect and the Component Lifecycle

Site Admin · 11 Sep 2026 · 8 views

useEffect and the Component Lifecycle

useEffect lets a component perform side effects after it renders, like fetching data, subscribing to events, or changing the document title.

Basic effect

import { useEffect } from 'react';

useEffect(() => {
  document.title = 'Dashboard';
}, []);

The first argument is the effect function. The second argument, the dependency array, controls when the effect runs.

The dependency array

An empty array runs the effect once after the first render. With values listed, the effect re-runs whenever any dependency changes. With no array at all, the effect runs after every render, which is rarely what you want.

useEffect(() => {
  console.log(userId);
}, [userId]);

Fetching data

Data fetching belongs in useEffect. Combine it with state:

const [data, setData] = useState([]);
useEffect(() => {
  fetch('/api/posts')
    .then((res) => res.json())
    .then(setData);
}, []);

Cleanup

Effects that set up subscriptions or timers should return a cleanup function:

useEffect(() => {
  const timer = setInterval(tick, 1000);
  return () => clearInterval(timer);
}, []);

React calls the cleanup before the next effect run and before the component unmounts. This prevents memory leaks and orphaned timers.

Common mistakes

Forgetting dependencies causes stale data; adding unstable values causes effects to run too often. Keep effect bodies focused, and consider separating concerns into multiple effects when a component does unrelated work.

Key Points

  • useEffect runs side effects after render.
  • The dependency array decides when an effect reruns.
  • Empty array means run once after mount.
  • Return a cleanup function for subscriptions and timers.
  • Keep effects focused and honest about dependencies.
Share this post:

Comments (0)

Please login or register to comment.