Cleanup Function in useEffect Hook

 In React's useEffect hook, a cleanup function is used to perform cleanup operations before the component unmounts or before the effect runs again (in the case of dependencies changing). It ensures that side effects such as event listeners, subscriptions, or timers are properly cleaned up to avoid memory leaks or unintended behavior.

Syntax
    useEffect(() => {
      // Side effect logic here
      return () => {
        // Cleanup logic here (optional)
      };
    }, [dependencies]);


useEffect with Dependency Array (optional): A list of values that the effect depends on. React re-runs the effect when any value in this array changes.

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

export default function App() {
 
  var [fcount,scount] = useState(0);
  useEffect(()=>{
    console.log(fcount)
  },[fcount])

  return (
    <div>
      <p>You clicked {fcount}</p>
      <button onClick={()=>scount(fcount+1)}>
        Counting..
      </button>
     
    </div>
  )
}

Syntax of
useEffect
with Cleanup Function:


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

  export default function App() {

    var [fshow, sshow] = useState(false);

    return (
      <div>

        <button onClick={()=>{sshow(!fshow)}}>
          Show Data..
        </button>
        {fshow && <Child />}

      </div>
    )
  }

  function Child(){

    useEffect(()=>{

      var i = 0
      setInterval(()=>{
        console.log('hello-'+1)
        i++
      },1000)

      // cleanup function
      return function(){
        // cleanup Function in useEffect (unmount the side effects)
        console.log("callback function unmounted")
      }

    },[])

    return <h2>Child</h2>

  }

Key Points:

Purpose of Cleanup:

  • Prevent resource leaks (e.g., unsubscribing from APIs, clearing timers).
  • Remove event listeners or subscriptions added in the effect.

Return a Function:

  • The cleanup function is returned from the useEffect hook. React calls it before the component unmounts or before running the effect again if dependencies have changed.

Dependency Array:

  • If the dependency array is empty ([]), the cleanup happens only when the component unmounts.
  • If there are dependencies, cleanup occurs whenever the dependencies change.