DEV Community

Nikhil
Nikhil

Posted on • Updated on

React: useEffect vs useLayoutEffect

If you have just started working on React or have ever written a functional component, I am pretty sure that you may have come across useEffect hook and you may know that it is used to perform some side effects like data fetching, sending HTTP requests, etc. But in this post we will talk about another react hook called useLayoutEffect and see how it is different from useEffect hook.

useLayoutEffect

To be honest there is not much difference between useEffect and useLayoutEffect the only noticable difference is that useLayoutEffect runs before browser paints DOM elements on the screen as you can see in the image below.

Alt Text

Credits- Donavon Github

As you can see in the image useEffect runs after the UI is painted. The only case where useLayoutEffect is useful and should be preferred over useEffect is when you are directly making DOM changes. As DOM changes would be done before it is painted on the screen and thus making the experience smooth.

Conclusion

One should prefer useEffect most of the time until and unless you are mutating DOM or want to do some performance measurements.

Wrap Up!

Thank you for your time!! Let's connect to learn and grow together. LinkedIn
Buy Me A Coffee

Top comments (0)