0
0
ReactHow-ToBeginner · 3 min read

ComponentWillUnmount Equivalent in React Hooks Explained

In React hooks, the ComponentWillUnmount lifecycle method is replaced by the cleanup function inside useEffect. You return a function from useEffect that React calls when the component unmounts to clean up resources or subscriptions.
📐

Syntax

The cleanup function inside useEffect runs when the component unmounts or before the effect runs again. It looks like this:

  • useEffect(() => { - sets up the effect
  • return () => { ... } - cleanup function called on unmount
  • [] - empty dependency array means effect runs once on mount and cleanup on unmount
javascript
useEffect(() => {
  // setup code here
  return () => {
    // cleanup code here (runs on unmount)
  };
}, []);
💻

Example

This example shows a component that sets up a timer when it mounts and clears the timer when it unmounts using the cleanup function in useEffect.

javascript
import React, { useState, useEffect } from 'react';

function Timer() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    const intervalId = setInterval(() => {
      setCount(c => c + 1);
    }, 1000);

    return () => {
      clearInterval(intervalId); // cleanup on unmount
      console.log('Timer cleaned up');
    };
  }, []);

  return <div>Seconds passed: {count}</div>;
}

export default Timer;
Output
Seconds passed: 0 (updates every second) Console on unmount: 'Timer cleaned up'
⚠️

Common Pitfalls

Common mistakes include:

  • Not returning a cleanup function from useEffect, causing resource leaks.
  • Omitting the dependency array, which causes the effect and cleanup to run on every render unnecessarily.
  • Trying to use componentWillUnmount directly in functional components instead of useEffect.
javascript
/* Wrong: No cleanup function, interval never cleared */
useEffect(() => {
  const id = setInterval(() => console.log('tick'), 1000);
}, []);

/* Right: Cleanup function clears interval */
useEffect(() => {
  const id = setInterval(() => console.log('tick'), 1000);
  return () => clearInterval(id);
}, []);
📊

Quick Reference

ConceptHook UsageWhen It Runs
Setup effectInside useEffect(() => { ... })After component mounts and on dependency change
Cleanup (ComponentWillUnmount)Return a function from useEffectBefore component unmounts or before next effect run
Run once on mount/unmountUse empty dependency array []Mount: effect runs once; Unmount: cleanup runs once

Key Takeaways

Use the cleanup function returned from useEffect to mimic ComponentWillUnmount behavior.
Always include an empty dependency array to run effect once and cleanup on unmount.
Forgetting cleanup causes memory leaks and unexpected bugs.
Functional components do not have lifecycle methods; useEffect replaces them.
Cleanup runs before the component unmounts or before the effect re-runs.