Does a functional component 'dismount' after a change in its state and does this result in previous useEffect callback return statements executing?
No, component dismounts only once at end of its life time, React allows to execute a callback with useEffect
hook by providing an empty dep array with a return
statement:
useEffect(() => {
return () => {
console.log("unmounts");
};
}, []);
When component dismounts?
When its parent stops rendering it. See conditional rendering.
Could you help me understand, in general or in the example in my question, when the return statement of useEffect executes?
Depends on the dep array:
- if it's empty
[]
, on unmount.
- if it has dependencies
[value1,value2]
, on dependencies change (shallow comparison).
- if it has no dependencies (no 2nd argument for
useEffect
) it runs on every render.
See follow up question useEffect in depth / use of useEffect?
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…