This is a fairly common interview question if React is part of the project's stack. It's worth starting with the fact that both hooks, useEffect and useLayoutEffect, are used to work with side effects, and the main difference between them is when they run.
useEffect
It fires after React has rendered the component and the browser has already painted the changes to the screen, which is why this hook does not block UI painting. In terms of the lifecycle, useEffect is similar to componentDidMount, which also fires only after the component is mounted in the DOM and fully available.
Typical use cases:
- API requests to fetch data;
- Subscriptions (event listeners, WebSocket);
useLayoutEffect
It fires after React has updated the DOM, but before the browser paints the page. Because of this, it blocks UI painting until the code inside the hook has finished running. This hook is used when you need to work with the DOM synchronously. In simple terms: useLayoutEffect is needed when you have to adjust something in the DOM so that the user never sees it.
Typical use cases:
- Measuring the width or height of elements;
- Changing the scroll position;
- Synchronously changing styles;
- Avoiding flickering or UI jumps (the most common case);