What is the real difference between React useEffect and useLayoutEffect?
If you are a React.js developer, you will know that these are widely used React.js hooks when doing frontend development. Most of us always have a doubt when selecting these functions since they do pretty much the same.
So today, let's talk about the real difference between them.
If you see the above functions they are exact same, the only difference they are having is the “Layout” in the method signature. But the real difference is the time they will be called. Let’s go to more details
UseEffect
This runs asynchronously after rendered elements are printed on the screen. So basically what happened it this.
UseLayoutEffect
This runs synchronously after the render but before elements are printed on the screen.
Now you know the difference between these two methods. Let see when to use them
Should I useEffect or useLayoutEffect?
In most cases, we will be using useEffect but in some cases, you will be experienced that your component is flickering when displaying, then you can switch to useLayoutEffect. But be careful when using useLayoutEffect since it is synchronous, there will be a performance hit. Because UI won’t be updated until this method execution is finished.
Thanks
If you like this post, you can read more articles on my personal blog devpubba.com.