Hackforge Academy

Category: react

What Is an Effect Cleanup Function?

Published on 27 Oct 2026

Explanation

A cleanup function releases resources created by an effect. React calls it before rerunning the effect with changed dependencies and when the component unmounts.

Code:

useEffect(() => {
  const id = setInterval(() => console.log('Tick'), 1000);

  return () => clearInterval(id);
}, []);

Explanation

Remove event listeners when they are no longer needed. This prevents duplicate handlers and avoids retaining references after a component unmounts.

Code:

useEffect(() => {
  const handleResize = () => setWidth(window.innerWidth);
  window.addEventListener('resize', handleResize);

  return () => {
    window.removeEventListener('resize', handleResize);
  };
}, []);

Explanation

Subscriptions and persistent connections should be closed when the effect ends. If a dependency changes, React cleans up the old connection before setting up the new one.

Code:

useEffect(() => {
  const socket = new WebSocket(`wss://example.com/rooms/${roomId}`);

  return () => socket.close();
}, [roomId]);

Explanation

An older request may finish after a newer request and overwrite the latest data. Use AbortController where supported, or a cleanup flag, to prevent obsolete results from updating the UI.

Code:

useEffect(() => {
  const controller = new AbortController();

  fetch(`/api/users/${userId}`, { signal: controller.signal })
    .then((res) => res.json())
    .then(setUser)
    .catch((error) => {
      if (error.name !== 'AbortError') console.error(error);
    });

  return () => controller.abort();
}, [userId]);

Explanation

When a dependency changes, React first runs the previous cleanup and then runs the new setup. This makes cleanup useful for keeping subscriptions and connections synchronized with current props or state.

Code:

useEffect(() => {
  console.log('Subscribe to:', topic);
  subscribe(topic);

  return () => {
    console.log('Unsubscribe from:', topic);
    unsubscribe(topic);
  };
}, [topic]);

πŸš€ Learn Spring Boot with real-world projects

πŸ’‘ Build REST APIs step by step

🧠 Improve backend development skills

🎯 Get career-ready practical training

Join Our Free WhatsApp Community

Direct access to niche-specific mentors and peers on WhatsApp.

🐍

Python Community

Discuss Django, FastAPI, AI integration, and automation scripts with 15k+ developers.

Join Python Community
βš›οΈ

React Community

Master Next.js, Framer Motion, and State Management. Share your latest UI components.

Join React Community
β˜•

Java Community

Deep dives into Spring Boot, Microservices architecture, and high-performance backend ops.

Join Java Community