Q22: What is the difference between useEffect and useLayoutEffect?
useEffect: Runs asynchronously after the DOM updates are committed and screen paint completes. Prevents blocking browser painting.useLayoutEffect: Runs synchronously after DOM updates are committed but before the browser paints the screen. Use strictly to measure DOM geometry and prevent visual layout flicker.
DOM Measurement with useLayoutEffect
useLayoutEffect(() => {
// Read DOM measurements synchronously before browser paint
const { height } = ref.current.getBoundingClientRect();
setElementHeight(height);
}, []);💡 Measuring and updating state inside useLayoutEffect prevents visual layout flickering before screen paint.
Key Takeaways
useLayoutEffectblocks browser paint until execution completes.- Use
useLayoutEffectto read DOM dimensions and apply scroll positioning before user visual paint.
Knowledge Check
Which effect Hook should be chosen if updating state causes visible screen element flickering when using useEffect?