0
0
Reactframework~5 mins

Unmounting phase in React

Choose your learning style9 modes available
Introduction

The unmounting phase is when a React component is removed from the screen. It helps clean up things like timers or event listeners so the app stays fast and bug-free.

When you want to stop a timer or interval to save resources.
When you need to remove event listeners to avoid memory leaks.
When cleaning up subscriptions to external data sources before the component disappears.
When resetting or clearing any data related to the component before it goes away.
Syntax
React
useEffect(() => {
  // setup code here
  return () => {
    // cleanup code here runs on unmount
  };
}, []);

The cleanup function inside useEffect runs when the component unmounts.

Passing an empty array [] as the second argument means the effect runs once and cleans up on unmount.

Examples
This example sets a timer and clears it when the component unmounts to stop the timer.
React
useEffect(() => {
  const timer = setInterval(() => {
    console.log('Tick');
  }, 1000);

  return () => {
    clearInterval(timer);
  };
}, []);
This example adds a window resize listener and removes it on unmount to avoid errors.
React
useEffect(() => {
  function onResize() {
    console.log('Window resized');
  }
  window.addEventListener('resize', onResize);

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

This component shows seconds passed, increasing every second. When the component is removed, the timer stops and logs a message.

React
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);
      console.log('Timer stopped');
    };
  }, []);

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

export default Timer;
OutputSuccess
Important Notes

Always clean up timers, listeners, or subscriptions in the unmount phase to keep your app smooth.

Without cleanup, your app might slow down or behave strangely over time.

Summary

The unmounting phase lets you clean up before a component disappears.

Use the cleanup function inside useEffect to stop timers or remove listeners.

This keeps your app fast and prevents bugs.