Skip to main content
InterviewHubPRO
Section Overview
Q240

Question 240 of 407

Part 8: Advanced React Patterns, Portals & Performance (152 - 261)

59%
React Core & Hooks (407 Qs)•Part 8: Advanced React Patterns, Portals & Performance (152 - 261)

What are the differences between useEffect and useLayoutEffect hooks?

junior LevelMost AskedCode ExampleHooksFormsPerformance

Both useEffect and useLayoutEffect share identical signatures, but differ in when they execute relative to DOM mutation and browser painting.

FeatureuseEffectuseLayoutEffect
Execution TimingAsynchronous (after browser paint)Synchronous (after DOM mutation, before paint)
Blocks Visual Render?NoYes (blocks visual paint until callback finishes)
Primary Use CasesAPI calls, subscriptions, timers, loggingDOM measurements (scroll position, tooltip placement)
Performance ImpactSmooth 60fps renders without jankCan cause screen freezing if computations are heavy

Code Example

jsx
import { useState, useLayoutEffect, useRef } from 'react';

export function TooltipTarget({ targetRect }) {
  const tooltipRef = useRef(null);
  const [position, setPosition] = useState({ top: 0, left: 0 });

  // useLayoutEffect runs BEFORE the browser paints, avoiding visual flicker
  useLayoutEffect(() => {
    if (tooltipRef.current && targetRect) {
      const height = tooltipRef.current.offsetHeight;
      setPosition({ top: targetRect.top - height - 8, left: targetRect.left });
    }
  }, [targetRect]);

  return <div ref={tooltipRef} style={{ position: 'fixed', top: position.top, left: position.left }}>Tooltip</div>;
}