I am trying to understand the useEffect hook in-depth.
I would like to know when to use which method and why?
1.useEffect with no second
useEffect(callback)
Runs on every component render.
Typically used for debugging, analogous to function's body execution on every render:
const Component = () => {
callback()
return <>>;
};
Note: There is still a difference, in execution time (see the next note). Check this sandbox logs.
useEffect(callback,[])
Runs once on a component mount.
Usually used for initializing components state by data fetching etc.
Note: The callback executed after the render phase (Known "Gotcha").
useEffect(callback,[arg])
Runs on change of arg value.
"On Change" refers to shallow comparison with the previous value of arg.
I.e compares the value of arg from the previous render and the current one, prevArg === arg ? ~Do nothing~ : callback().
Usually used to run events on props/state change.
Note: Multiple dependecies can be provided:
[arg1,arg2,arg3...]