Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between code inside useEffect with no dependencies and outside of it?

Tags:

reactjs

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?

like image 225
Anubhav Avatar asked Dec 12 '19 16:12

Anubhav


2 Answers

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.

like image 183
Dupocas Avatar answered Sep 30 '22 15:09

Dupocas


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.

like image 24
Jackson Kamya Avatar answered Sep 30 '22 16:09

Jackson Kamya