Home > Software design >  when I have multiple use effects which useeffect cleanup function will be called
when I have multiple use effects which useeffect cleanup function will be called

Time:09-27

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

CodePudding user response:

Hooks are called in declaration order Edit fancy-firefly-qw543

CodePudding user response:

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>
    )
};
  • Related