DEV Community

Cover image for UseEffect and useLayoutEffect differences
Sandeep
Sandeep

Posted on • Updated on

UseEffect and useLayoutEffect differences

Today we discuss what is difference between on those hooks in react and when we use it.

useEffect is the most popular hooks and came to replace componentDidMount, componentDidUpdate, and componentWillUnmount.

Implementation is the same as useEffect, but useLayoutEffect, will wait until React finishes with all its DOM manipulations and then do yours. This is best difference.

const App = () => {

  useLayoutEffect(() => {
    console.log("this is useLayoutEffect");
  }, []);

  useEffect(() => {
    console.log("this is useEffetct");
  }, []);

  console.log("Render of component");

  return <div>Hello, India Walo</div>;
};
Enter fullscreen mode Exit fullscreen mode

Output in console

`Render of component
this is useLayoutEffect
this is useEffetct

`

This hook is synchronous, meaning that React waits for all the logic within the hook to complete and execute immediately after the rendering phase, but before drawing the changes on the screen.
The steps is the following:

  1. Enter the render phase.
  2. Execute useLayoutEffect.
  3. Draw the changes on the screen.
  4. Execute useEffect.

Discussion (0)