1

I am very new to react and I am experimenting with react hooks

lets say I have a component that has multiple useeffect hooks. both the useeffect hooks have a cleanup function. My questions are

  1. in what order those cleanup function be called
  2. will both the functions be called every time a component unmounts
  3. any real life example of having multiple cleanup functions
Nisha Dave
  • 669
  • 1
  • 9
  • 25

2 Answers2

0

Hooks are called in declaration order as mentioned in Rules of hooks.

So goes for clean-up functions, therefore both cleanup functions will be called on component's unmount.

Refer to "uses of useEffect" for detailed explanation on functionalitty differences of cleanup callbacks.

Moreover, test your assumptions by running simple logs example:

const Component = ({ isMounted }) => {
  useEffect(() => {
    console.log("Mount 1");

    return () => {
      console.log("Mount 1 out");
    };
  }, []);

  useEffect(() => {
    console.log("Mount 2");

    return () => {
      console.log("Mount 2 out");
    };
  }, [isMounted]);

  return <>Test</>;
};

export default function App() {
  const [isMounted, toggle] = useReducer((p) => !p, true);

  useEffect(() => {
    console.log("1");

    return () => {
      console.log("1 out");
    };
  }, [isMounted]);

  useEffect(() => {
    console.log("2");

    return () => {
      console.log("2 out");
    };
  }, [isMounted]);

  return (
    <>
      <button onClick={toggle}>{isMounted ? "unmount" : "mount"}</button>
      <div>{isMounted && <Component {...{ isMounted }} />}</div>
    </>
  );
}

Edit fancy-firefly-qw543

Dennis Vash
  • 50,196
  • 9
  • 100
  • 118
0

in what order those cleanup function be called (run the function at the end)

enter image description here

will both the functions be called every time a component unmounts

Yes, as you can see in this example, all use effects with an return statement (as "unmount") are executed every time the component unmounts.

any real life example of having multiple cleanup functions

import { useState, useEffect } from 'react';

const Welcome = () => {
    useEffect(() => {
        console.log("useEffect 1")
        return () => {
            console.log("useEffect1 cleanup")
        }
    }, [])


    useEffect(() => {
        console.log("useEffect 2")
        return () => {
            console.log("useEffect2 cleanup")
        }
    }, [])


    useEffect(() => {
        console.log("useEffect 3")
        return () => {
            console.log("useEffect3 cleanup")
        }
    }, [])
    return (
        <div>Welcome !</div>
    )
}


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



    return (
        <div>
            {show && <Welcome />}
            <button type='button' onClick={()=>setShow((prev) => !prev)}>unmount sidebar</button>
        </div>
    )
};
ABDULLOKH MUKHAMMADJONOV
  • 4,249
  • 3
  • 22
  • 40