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
- in what order those cleanup function be called
- will both the functions be called every time a component unmounts
- any real life example of having multiple cleanup functions
CodePudding user response:
Hooks are called in declaration order
CodePudding user response:
in what order those cleanup function be called (run the function at the end)
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>
)
};