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
3.useEffect with some arguments passed in the second parameter useEffect(()=>{},[arg])
it will run first then it will run again if arg change
Your forget also to ask what about the return inside the useEffect... Its uses for cleanup it will run when component dismount
If you’re familiar with React class lifecycle methods, you can think of useEffect Hook as componentDidMount, componentDidUpdate, and componentWillUnmount combined.
1.useEffect with no second paraments : This is used when we want something to happen either when the component just mounted, or if it has been updated. Conceptually, we want it to happen after every render.
2.useEffect with second paraments as [] : This is used when we want something to happen at the time of mounting of the component, if only executes once at the time of mounting.It is closer to the familiar componentDidMount and componentWillUnmount.
3.useEffect with some arguments passed in the second parameter:This is used when we want something to happen at the time when the pramter passed eg. args have changed in your case.
For more info. check here: https://reactjs.org/docs/hooks-effect.html
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...]