0
0
ReactConceptBeginner · 3 min read

What is Unmounting in React: Explanation and Example

In React, unmounting is the process when a component is removed from the UI and React cleans up its resources. It happens when the component is no longer needed, and React runs any cleanup code inside the useEffect hook's return function before removing the component.
⚙️

How It Works

Unmounting in React is like cleaning up your workspace after finishing a task. When a component is no longer shown on the screen, React removes it from the page. Before it does that, React gives you a chance to tidy up by running cleanup code.

This cleanup happens inside the useEffect hook if you return a function from it. This function runs right before the component disappears, letting you stop timers, cancel network requests, or remove event listeners. Think of it as turning off the lights and locking the door when you leave a room.

💻

Example

This example shows a component that sets a timer when it appears and clears it when it unmounts.

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

function Timer() {
  useEffect(() => {
    const intervalId = setInterval(() => {
      console.log('Timer tick');
    }, 1000);

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

  return <div>Timer is running. Check the console.</div>;
}

export default function App() {
  const [show, setShow] = useState(true);

  return (
    <div>
      <button onClick={() => setShow(!show)}>
        {show ? 'Hide' : 'Show'} Timer
      </button>
      {show && <Timer />}
    </div>
  );
}
Output
When the Timer component is shown, the console logs 'Timer tick' every second. When you click the button to hide it, the console logs 'Timer cleaned up on unmount' and stops logging ticks.
🎯

When to Use

Use unmounting cleanup to avoid memory leaks and unwanted side effects. For example, if your component starts a timer, listens to window events, or fetches data, you should clean these up when the component goes away.

This keeps your app fast and prevents bugs caused by code running after the component is gone. Common cases include stopping intervals, removing event listeners, and canceling API calls.

Key Points

  • Unmounting means removing a component from the UI.
  • React runs cleanup code inside useEffect return functions before unmounting.
  • Cleanup prevents memory leaks and stops side effects.
  • Common cleanup tasks include clearing timers and removing event listeners.

Key Takeaways

Unmounting is when React removes a component from the screen and cleans up.
Use the return function in useEffect to run cleanup code on unmount.
Always clean timers, event listeners, and subscriptions to avoid bugs.
Unmounting helps keep your app efficient and bug-free.