Sobes.tech
Middle

When is useLayoutEffect called and how does it differ from useEffect?

sobes.tech AI

Answer from AI

useLayoutEffect is called synchronously immediately after React has applied all changes to the DOM, but before the browser has painted the updates on the screen. This allows performing operations that need to happen before the visual update, such as measuring element sizes or synchronizing state with the DOM.

Unlike useEffect, which is called asynchronously after the browser has painted the changes, useLayoutEffect blocks the painting until its code has finished.

Example:

useLayoutEffect(() => {
  const height = ref.current.clientHeight;
  // You can immediately update the state to avoid flickering
  setHeight(height);
}, []);

useEffect(() => {
  // You can perform side effects here that do not affect the visual display
}, []);