I am having trouble wrapping my head around code that is inside a useEffect without dependencies vs. code that is simply outside useEffect.
For e.g, a simplistic example:
const func1 = () => {
console.log("Apple")
useEffect(() => {
console.log("Banana")
})
return (//...JSX)
}
I believe BOTH Apple
and Banana
would be called at re-renders, so why use useEffect at all?
The standard answer I've heard is that Apple
will be called at every re-render but Banana
will be called only when a state/prop changes.
But a state / prop changing should almost always cause a re-render anyway so is there really a benefit of having that inside useEffect?
Yes, you are right! Both codes run on each render, but the difference is when.
Consider the following
const Component = () =>{
const ref = useRef(null)
console.log(ref.current) // null
useEffect(() => console.log(ref.current) /*div*/)
return <div ref={ref} />
}
useEffect
runs after the component is mounted. So for your example useEffect
is useless but if you need to access a value which is only available after the component is mounted (measure the DOM for example) effects are usually the way to go.
In your example code, I don't think there is a benefit in having that in the useEffect hook. But the 2 lines of code are executed at different times. The one outside useEffect is not hindered by the component life cycle - I think it is called as the component is being rendered. The one inside the useEffect hook however is called when the component has been mounted or updated as stated here in the react docs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With