π React useLayoutEffect β Complete In-Depth Guide
1. π§ Introduction
What is useLayoutEffect?
useLayoutEffect is a React Hook that runs synchronously after DOM mutations but before the browser paints.
useEffect, but with a critical difference:
useEffectβ runs after paint (async)useLayoutEffectβ runs before paint (sync)
Why it is Important in React
React normally:- Updates DOM
- Lets browser paint
- Then runs effects (
useEffect)
- Measure DOM size/position
- Make visual adjustments before user sees anything
- Avoid flickering/jumps
useLayoutEffect becomes essential.
When and Why We Use It
UseuseLayoutEffect when:
β You need to read layout
- Element width/height
- Scroll position
- Bounding boxes
β You need to mutate DOM before paint
- Adjust styles
- Reposition elements
β You want to prevent visual flicker
β When NOT to use it
Avoid it when:- You are doing data fetching
- You are running non-UI logic
- You donβt depend on layout
2. βοΈ Concepts / Internal Workings
React Rendering Phases (Critical to Understand)
React works in two main phases:1. Render Phase (Virtual DOM)
- Pure calculation
- No DOM mutations
2. Commit Phase (DOM updates)
Inside commit phase:How useLayoutEffect Works Internally
- React finishes DOM updates
-
Before browser paints:
- Runs all
useLayoutEffectcallbacks
- Runs all
-
Blocks paint until:
- All layout effects complete
User never sees intermediate DOM states
Visual Timeline
Relationship with Other Hooks
πΉ vs useEffect
πΉ vs useRef
useLayoutEffect+useRefis a common combo- Used for DOM access before paint
πΉ vs useEffect Cleanup
Cleanup timing:
useLayoutEffectcleanup β runs before next layout effect / before DOM changesuseEffectcleanup β runs later
Strict Mode Behavior (React 18+)
In development:useLayoutEffectruns twice (mount + cleanup + mount)
- Side effects
- Unsafe mutations
3. π» Syntax & Examples
Basic Syntax
Example 1: Measuring DOM Size
Example 2: Prevent Layout Shift (Tooltip Positioning)
Example 3: Scroll Position Control
Example 4: DOM Mutation Before Paint
Mini Example: Difference Demo
4. β οΈ Edge Cases / Common Mistakes
β 1. Overusing useLayoutEffect
Problem:
- Blocks rendering
- Causes performance lag
Fix:
π Default touseEffect unless layout is required
β 2. Causing Forced Reflows
- Layout recalculation
- Performance bottlenecks
β 3. Infinite Loops
- Re-render β layout effect β setState β loop
β 4. SSR Warning (Important)
useLayoutEffect does nothing on server
React warns:
βuseLayoutEffect does nothing on the serverβ
Fix:
β 5. Visual Flicker Misuse
UsinguseEffect instead:
- Flicker
- Layout shift
useLayoutEffect
β 6. Heavy Computation Inside
5. β Best Practices
βοΈ 1. Prefer useEffect by Default
Only use useLayoutEffect when:
- You must block paint
βοΈ 2. Keep It Lightweight
- API calls
- heavy loops
βοΈ 3. Batch DOM Reads & Writes
Bad:- Read first
- Then write
βοΈ 4. Use with useRef (Best Pairing)
βοΈ 5. Avoid State Updates If Possible
Prefer direct DOM updates when safe:βοΈ 6. Handle SSR Properly
Create abstraction:βοΈ 7. Measure Once, Cache Smartly
Avoid repeated layout reads:- Use refs
- Memoize values
βοΈ 8. Combine with requestAnimationFrame (Advanced)
π§Ύ Final Mental Model
π Think ofuseLayoutEffect as:
βA hook for reading and fixing layout before the user sees anything.β
π Golden Rule
- 90% of cases β useEffect
- 10% β useLayoutEffect (only for layout-critical work)
Below is a senior-level, depth-focused interview set on
useLayoutEffect.
Each question is designed to probe mental models, trade-offs, and real-world decision-making, not just API recall.
π§ Advanced useLayoutEffect Interview Questions (with Answers)
1. What problem does useLayoutEffect solve that useEffect cannot?
β Strong Answer
The core problem is visual consistency before paint.-
useEffectruns after the browser paints, so any DOM reads/writes can cause:- Flicker
- Layout shifts (CLS issues)
-
useLayoutEffectruns before paint, allowing:- Synchronous DOM reads
- Immediate DOM corrections
The user only sees the final, corrected layout.
Example
π‘ Why this matters
Because render β visually stable UI. Layout effects ensure visual correctness before display.2. Walk through the exact execution order of useLayoutEffect in Reactβs lifecycle.
β Strong Answer
React commit phase order:Key Insight
useLayoutEffectis part of the commit phase- It runs after DOM is updated but before paint
Why this design?
React separates:- Mutation phase β apply DOM
- Layout phase β measure/fix layout
- Passive phase β async side effects
3. Why is useLayoutEffect considered dangerous for performance?
β Strong Answer
Because it blocks the browserβs paint cycle.- Runs synchronously
- Prevents UI from updating until it completes
Impact
- Long tasks β UI freezes
- Multiple layout effects β cumulative delay
Example
Better
π‘ Trade-off
4. How does useLayoutEffect interact with the browserβs rendering pipeline?
β Strong Answer
Browser pipeline:Key Point
- It runs after layout calculation but before paint
- Any DOM reads (e.g.,
getBoundingClientRect) are accurate
Risk
If you:- Read β write β read again π You trigger forced synchronous reflow
5. Explain forced reflow and how useLayoutEffect can cause it.
β Strong Answer
Forced reflow happens when:- Browser must recalculate layout immediately
Example
Why dangerous?
- Breaks browser optimizations
- Causes layout thrashing
Fix
π Batch reads and writes:6. Why does React warn about useLayoutEffect on the server?
β Strong Answer
Because:- There is no DOM on the server
- No layout or paint phase exists
useLayoutEffect cannot run meaningfully
Warning
βuseLayoutEffect does nothing on the serverβ
Solution
Why important?
Prevents:- Hydration mismatches
- Console warnings
7. How does useLayoutEffect behave in React Strict Mode?
β Strong Answer
In development:-
React runs:
- setup β cleanup β setup
Why?
To detect:- Side effects
- Non-idempotent logic
Example
Implication
Your effect must be:- Pure
- Repeatable
8. When would you choose useLayoutEffect over CSS solutions?
β Strong Answer
Prefer CSS when possible. UseuseLayoutEffect only when:
- Layout depends on runtime measurements
Example
β Avoid JS:When JS is needed:
- Dynamic tooltip positioning
- Canvas measurements
- Virtualized lists
9. How would you implement a flicker-free tooltip system?
β Strong Answer
Key requirement:- Measure target
- Position tooltip
- Do it before paint
Solution
Why not useEffect?
Because:
- Tooltip would render at wrong position first
- Then jump β bad UX
10. What are the trade-offs between useLayoutEffect and requestAnimationFrame?
β Strong Answer
Combined usage
Insight
useLayoutEffect= correctnessrAF= smoothness
11. Can useLayoutEffect cause infinite render loops? How?
β Strong Answer
Yes, if state updates are not controlled.- render β layout effect β setState β render β β¦
Fix
- Use correct dependencies
- Guard updates
12. Why is useLayoutEffect commonly paired with useRef?
β Strong Answer
Because:useRefgives direct DOM accessuseLayoutEffectguarantees DOM is ready
Pattern
Why not during render?
Because:- DOM doesnβt exist yet
13. How does useLayoutEffect behave with concurrent rendering?
β Strong Answer
Important nuance:- Concurrent rendering affects render phase
useLayoutEffectruns only in commit phase
- It is always synchronous
- Cannot be interrupted
Implication
- Still blocks paint
- Not βconcurrent-friendlyβ
14. What happens if multiple useLayoutEffect hooks exist?
β Strong Answer
They run:- In order of declaration
- All before paint
Example
Insight
- Order matters for DOM dependencies
15. How would you debug a layout shift issue in React?
β Strong Answer
Steps:- Identify flicker/jump
-
Check:
- Is measurement happening in
useEffect?
- Is measurement happening in
-
Move to
useLayoutEffect
Tools
- Chrome DevTools β Performance tab
- Layout shift visualization
Root Cause
- DOM updated after paint
16. Why is useLayoutEffect not suitable for data fetching?
β Strong Answer
Because:- It blocks paint
- Fetching is async and non-visual
Bad
Good
Principle
π Layout effects = visual correctness only17. How would you design a custom hook that safely uses useLayoutEffect?
β Strong Answer
Abstract SSR + layout logic:Benefits
- SSR-safe
- Reusable
- Encapsulates complexity
18. What mental model should developers use for useLayoutEffect?
β Strong Answer
Think of it as:βA synchronous hook to read and fix layout before the user sees anything.β
Decision heuristic
Ask:- Does this affect visual layout immediately?
- Will the user see a wrong state before correction?
useLayoutEffect
Else β useEffect
π₯ Final Insight
Senior engineers donβt just know howuseLayoutEffect works β they know:
- When NOT to use it
- How it impacts rendering performance
- How it interacts with the browser pipeline
Below is a senior-level MCQ set on
useLayoutEffect designed to test deep mental models, edge cases, and real-world reasoning.
π§ Advanced MCQs β useLayoutEffect
1. You observe a flicker when positioning a dropdown after render. What is the most correct fix?
Options:
A. Wrap inrequestAnimationFrame
B. Replace with useLayoutEffect
C. Move logic inside render
D. Use setTimeout
β Correct Answer: B
Explanation:
-
The flicker occurs because:
useEffectruns after paint- Initial incorrect UI is visible
useLayoutEffect runs before paint, preventing flicker.
Why others are wrong:
- A:
requestAnimationFramestill runs after paint β flicker remains - C: DOM is not available during render
- D: Makes timing worse (even later)
2. What is the primary performance risk of using useLayoutEffect excessively?
Options:
A. Memory leaks B. Blocking browser paint C. Delayed network requests D. Increased bundle sizeβ Correct Answer: B
Explanation:
useLayoutEffectis synchronous and blocks paint- Long operations β visible UI lag
Why others are wrong:
- A: Possible, but not primary risk
- C: Not related
- D: Hook usage doesnβt affect bundle size
3. In what order do these logs execute?
Options:
A. render β effect β layout B. render β layout β effect C. layout β render β effect D. render β effect β layoutβ Correct Answer: B
Explanation:
Execution order:Why others are wrong:
- A/D: Incorrect ordering of layout/effect
- C: Layout cannot run before render
4. What happens if useLayoutEffect triggers a state update on every render?
Options:
A. React ignores it B. It runs once C. Infinite render loop D. React batches updates and stops loopβ Correct Answer: C
Explanation:
-
setStateinside layout effect:- Causes re-render
- Effect runs again β loop
Why others are wrong:
- A: React does not ignore
- B: Not true without dependency control
- D: Batching doesnβt prevent loops
5. Why does React warn about useLayoutEffect in SSR?
Options:
A. It causes hydration failure B. It blocks rendering on server C. No DOM/layout exists on server D. It runs twice on serverβ Correct Answer: C
Explanation:
-
Server has:
- No DOM
- No layout/paint
Why others are wrong:
- A: Not inherently true
- B: Server rendering is synchronous anyway
- D: Incorrect
6. Which scenario justifies using useLayoutEffect over CSS?
Options:
A. Setting static height B. Dynamic measurement-based positioning C. Styling hover states D. Applying theme colorsβ Correct Answer: B
Explanation:
-
CSS cannot handle:
- Runtime measurements
- Dynamic positioning logic
Why others are wrong:
- A/C/D: Better handled with CSS
7. What is a forced reflow?
Options:
A. React re-render cycle B. Browser recalculating layout synchronously C. DOM repaint D. State update batchingβ Correct Answer: B
Explanation:
-
Happens when:
- Layout is recalculated immediately
-
Often triggered by:
- Read β write β read pattern
Why others are wrong:
- A/D: React concepts
- C: Paint β layout recalculation
8. Which code is most likely to cause layout thrashing?
Options:
A.β Correct Answer: D
Explanation:
-
Pattern:
- Read β Write β Read π Forces reflow
Why others are wrong:
- A: Single read/write
- B: Only reads
- C: Only write
9. In Strict Mode, what happens to useLayoutEffect?
Options:
A. Runs once B. Runs twice (mount + cleanup + mount) C. Skipped entirely D. Runs asynchronouslyβ Correct Answer: B
Explanation:
-
Dev-only behavior:
- Detect side effects
Why others are wrong:
- A: Not in Strict Mode
- C/D: Incorrect behavior
10. Which is the best use case for useLayoutEffect?
Options:
A. Fetching API data B. Logging analytics C. Measuring DOM before positioning D. Updating global stateβ Correct Answer: C
Explanation:
-
Layout measurement requires:
- DOM + sync execution before paint
Why others are wrong:
- A/B/D: Non-layout side effects β useEffect
11. What happens if useLayoutEffect contains heavy computation?
Options:
A. It runs in background B. UI becomes unresponsive C. React skips it D. It moves touseEffect automatically
β Correct Answer: B
Explanation:
- Blocks paint β freezes UI
Why others are wrong:
- A: Not async
- C/D: React does not optimize this
12. Which pairing is most common with useLayoutEffect?
Options:
A. useState B. useReducer C. useRef D. useMemoβ Correct Answer: C
Explanation:
useRefprovides DOM access- Required for layout measurements
13. Why shouldnβt you use useLayoutEffect for data fetching?
Options:
A. It doesnβt support async B. It blocks paint unnecessarily C. It causes memory leaks D. It fails in productionβ Correct Answer: B
Explanation:
-
Fetching is:
- Non-visual
- Async
14. What guarantees does useLayoutEffect provide?
Options:
A. Runs after paint B. Runs before DOM updates C. Runs after DOM updates but before paint D. Runs during renderβ Correct Answer: C
Explanation:
-
Key guarantee:
- DOM is updated
- UI not yet visible
15. How are multiple useLayoutEffect hooks executed?
Options:
A. Random order B. Parallel C. In declaration order D. Based on dependenciesβ Correct Answer: C
Explanation:
- Deterministic order
- Important for DOM dependencies
16. Which approach avoids SSR warnings?
Options:
A.β Correct Answer: C
Explanation:
- Safely switches behavior based on environment
17. Why might requestAnimationFrame be combined with useLayoutEffect?
Options:
A. To delay rendering B. To move work after paint C. To smooth animations after layout correction D. To avoid dependency arraysβ Correct Answer: C
Explanation:
-
Pattern:
- Layout fix β rAF β animation
18. What is the biggest conceptual difference between useEffect and useLayoutEffect?
Options:
A. Dependency handling B. Execution timing relative to paint C. Cleanup behavior D. Hook syntaxβ Correct Answer: B
Explanation:
- Everything else is same
- Timing is the core difference
π₯ Final Takeaway
These questions target whether a candidate understands:- Rendering pipeline
- Browser internals
- Performance implications
- When NOT to use
useLayoutEffect
Below is a senior-level coding problem set for
useLayoutEffect, designed around real-world UI systems, layout correctness, and performance trade-offs.
π§ Advanced Coding Problems β useLayoutEffect
1. Flicker-Free Tooltip Engine
π§© Problem
Build a tooltip component that:- Appears below a target element
- Repositions based on viewport constraints
- Never flickers or jumps
Constraints
- Must avoid layout shift
- Tooltip should flip (top/bottom) if space is insufficient
- No external libraries
Expected Behavior
- Tooltip appears in correct position immediately
- No visible repositioning
Edge Cases
- Near viewport edges
- Dynamic content size
- Window resize
β Solution Approach
-
Use
useReffor DOM nodes -
Use
useLayoutEffectto:- Measure target + tooltip
- Compute position
- Update state before paint
π‘ Why useLayoutEffect?
Prevents visible repositioning flicker.
2. Virtualized List with Dynamic Row Heights
π§© Problem
Render a large list where:- Each row has unknown height
- Only visible rows are rendered
Constraints
- Must measure row height dynamically
- Smooth scrolling
- No layout jumps
Expected Behavior
- Accurate scroll position
- No flickering rows
Edge Cases
- Rapid scroll
- Dynamic content updates
β Solution Approach
- Use
useLayoutEffectto measure row height after render - Store heights in a map
- Adjust scroll offsets
π‘ Insight
UsinguseEffect would cause incorrect scroll calculations initially.
3. Sticky Header Without Layout Shift
π§© Problem
Create a header that:- Becomes sticky after scrolling
- Does not cause content jump
Constraints
- Must maintain layout consistency
Expected Behavior
- Smooth transition
- No sudden shift
Edge Cases
- Resize
- Dynamic header height
β Solution
- Measure header height using
useLayoutEffect - Apply placeholder spacing
4. Auto-Scrolling Chat Window
π§© Problem
Implement chat UI that:- Scrolls to latest message automatically
- Does not show scroll jump
Constraints
- Only scroll if user is at bottom
Expected Behavior
- Smooth UX
Edge Cases
- User scrolls up manually
- Large message batches
β Solution
5. Resizable Panel System
π§© Problem
Create draggable panels:- Width updates in real-time
- Layout stays stable
Constraints
- No flicker
- High performance
Edge Cases
- Rapid drag
- Window resize
β Solution
- Track drag position
- Use
useLayoutEffectto sync DOM updates
6. Prevent Layout Shift on Image Load
π§© Problem
Images load asynchronously causing layout shifts.Constraints
- Maintain placeholder size
Expected Behavior
- No CLS (Cumulative Layout Shift)
β Solution
7. Dynamic Grid Masonry Layout
π§© Problem
Build Pinterest-style grid:- Items have variable heights
- Layout must be compact
β Solution
- Measure each item
- Calculate column placement in
useLayoutEffect
8. Drag-and-Drop Ghost Element Positioning
π§© Problem
While dragging:- Show ghost element following cursor
- Must match original element size
β Solution
9. Scroll Restoration System
π§© Problem
Restore scroll position when navigating back.β Solution
10. Adaptive Dropdown Width Matching Trigger
π§© Problem
Dropdown width should match trigger width.β Solution
11. Focus Trap Modal
π§© Problem
Ensure focus stays inside modal.β Solution
12. Measure Before Animation Starts
π§© Problem
Animate element from initial position.β Solution
13. Prevent Scroll Jump on Content Expansion
π§© Problem
Expanding content shifts scroll unexpectedly.β Solution
- Capture scroll position
- Restore after update
14. Multi-Step Form Progress Indicator Alignment
π§© Problem
Align progress bar with steps dynamically.β Solution
- Measure step positions using
useLayoutEffect
15. Detect Element Overflow
π§© Problem
Show βRead moreβ if content overflows.β Solution
16. Dynamic Canvas Drawing Based on Size
π§© Problem
Canvas must adapt to container size.β Solution
17. Sticky Sidebar with Dynamic Height
π§© Problem
Sidebar should not overflow viewport.β Solution
- Measure height and adjust maxHeight dynamically
18. Keyboard Navigation with Scroll Into View
π§© Problem
Focused item should scroll into view.β Solution
19. Collapsible Sections with Height Animation
π§© Problem
Animate height from0 β auto.
β Solution
- Measure full height first using
useLayoutEffect - Then animate
π₯ Final Takeaways
These problems test whether you can:- Control layout before paint
- Prevent flicker & layout shifts
- Handle DOM measurement correctly
- Balance performance vs correctness
Below are senior-level debugging challenges around
useLayoutEffect, modeled after real production bugsβsubtle, non-obvious, and rooted in React lifecycle + browser behavior.
π§ Debugging Challenges β useLayoutEffect
1. Infinite Render Loop via Measurement
π Buggy Code
β Whatβs Wrong
- Effect depends on
width - Effect updates
widthβ triggers re-render β loop
π€― Why It Happens
useLayoutEffectruns after every render where dependency changes- State update inside effect creates circular dependency
β Fixed Code
π‘ Best Practice
π Avoid putting derived state from DOM in dependency arrays π Use guards if needed2. Flicker Despite Using useLayoutEffect
π Buggy Code
β Whatβs Wrong
- Initial render still uses default position
- State update triggers second render
π€― Why It Happens
- First render happens before effect runs
- Even though itβs before paint, layout recalculation still causes shift
β Fix
π‘ Best Practice
π Avoid rendering incomplete layout β delay render if needed3. Layout Thrashing from Mixed Reads/Writes
π Buggy Code
β Whatβs Wrong
- Read β Write β Read pattern
π€― Why It Happens
- Browser forced to recalculate layout twice β expensive
β Fix
π‘ Best Practice
π Batch reads first, then writes4. SSR Warning in Production Logs
π Buggy Code
β Whatβs Wrong
useLayoutEffectused in SSR environment
π€― Why It Happens
- No DOM on server β React warns
β Fix
π‘ Best Practice
π Always handle SSR when using layout effects5. Janky Drag Performance
π Buggy Code
β Whatβs Wrong
- Runs on every drag update synchronously
π€― Why It Happens
- Blocks paint during rapid updates β lag
β Fix
π‘ Best Practice
π UseuseLayoutEffect only for critical layout corrections, not continuous updates
6. Stale DOM Reference
π Buggy Code
β Whatβs Wrong
- Ref might not be updated if conditional rendering
π€― Why It Happens
- Effect runs before ref is set in some cases
β Fix
π‘ Best Practice
π Always null-check refs7. Scroll Jump on Content Update
π Buggy Code
β Whatβs Wrong
- Forces scroll even if user scrolled up
π€― Why It Happens
- No user intent check
β Fix
π‘ Best Practice
π Respect user scroll behavior8. Double Execution in Strict Mode Breaks Logic
π Buggy Code
β Whatβs Wrong
- Library initializes twice in dev
π€― Why It Happens
- Strict Mode double-invokes effects
β Fix
π‘ Best Practice
π Make effects idempotent9. Incorrect Dependency Causing Missed Updates
π Buggy Code
β Whatβs Wrong
- Doesnβt update when target changes
π€― Why It Happens
- Missing dependency
β Fix
π‘ Best Practice
π Treat layout effects like pure functions of dependencies10. Measuring Before DOM Update Completes
π Buggy Code
β Whatβs Wrong
- Effect doesnβt depend on items
π€― Why It Happens
- Effect runs before new DOM is reflected
β Fix
π‘ Best Practice
π Always sync effect with DOM-changing state11. Hidden Performance Bottleneck
π Buggy Code
β Whatβs Wrong
- Heavy computation blocks paint
π€― Why It Happens
- Synchronous execution
β Fix
π‘ Best Practice
π Keep layout effects minimal12. Tooltip Misalignment on Resize
π Buggy Code
β Whatβs Wrong
- Doesnβt update on resize
π€― Why It Happens
- Effect only runs once
β Fix
π‘ Best Practice
π Handle environmental changes (resize, scroll)13. Memory Leak via Event Listener
π Buggy Code
β Whatβs Wrong
- No cleanup
π€― Why It Happens
- Listener persists after unmount
β Fix
π‘ Best Practice
π Always clean up side effects14. Race Condition with State Updates
π Buggy Code
β Whatβs Wrong
- Multiple state updates β multiple renders
π€― Why It Happens
- Each setState triggers render
β Fix
π‘ Best Practice
π Batch related state updates15. Animation Starts from Wrong Position
π Buggy Code
β Whatβs Wrong
- Animation starts after paint
π€― Why It Happens
- Initial frame rendered incorrectly
β Fix
π‘ Best Practice
π Use layout effect for initial animation setupπ₯ Final Insight
These bugs test whether you understand:- React commit phase deeply
- Browser rendering pipeline
- Performance trade-offs
- Real-world UI behavior
Below is a production-grade machine coding set focused on
useLayoutEffect.
These are the kinds of problems that test architecture, rendering correctness, performance, and real-world trade-offsβnot just implementation.
π§ Real-World Machine Coding Problems β useLayoutEffect
1. Smart Tooltip System (Flip + Collision Detection)
π Requirements
- Tooltip appears on hover
- Positions relative to target
- Flips (top/bottom/left/right) if space is insufficient
- Supports dynamic content
π― UI Behavior
- No flicker or jump
- Smooth appearance
- Accurate placement
π State / Data Flow
targetRecttooltipRectplacement
β οΈ Edge Cases
- Near viewport edges
- Scroll container offsets
- Dynamic tooltip size
π Performance Considerations
- Avoid repeated measurements
- Cache dimensions where possible
π Suggested Architecture
TooltipProvideruseTooltipPositionhook- Portal rendering
π Solution Approach
- Render tooltip offscreen initially
-
Use
useLayoutEffect:- Measure both elements
- Compute optimal placement
- Update state before paint
2. Virtualized Infinite List (Dynamic Heights)
π Requirements
- Render only visible items
- Support variable row heights
- Infinite scrolling
π― UI Behavior
- Smooth scroll
- No jump during measurement
π State
scrollTopvisibleRangeitemHeights
β οΈ Edge Cases
- Fast scrolling
- Resize events
- Data updates
π Performance
- Minimize reflows
- Avoid full list recalculation
π Architecture
- Windowing engine
- Height map cache
useLayoutEffectfor measurement
π Approach
- Render estimated height
- Measure real height in
useLayoutEffect - Adjust offsets
3. Drag-and-Drop Builder (Like Notion / Figma Layers)
π Requirements
- Drag elements vertically
- Show placeholder position
- Smooth reorder
π― Behavior
- Ghost element follows cursor
- Accurate drop preview
π State
dragIndexhoverIndexpositions
β οΈ Edge Cases
- Rapid drag
- Nested lists
π Performance
- Avoid blocking UI during drag
π Architecture
- Context for drag state
- Layout measurement hook
π Approach
- Measure all item positions in
useLayoutEffect - Calculate insertion index dynamically
4. Sticky Section Headers (Grouped List)
π Requirements
- Sections stick to top while scrolling
- Multiple groups
π― Behavior
- Smooth transitions between sections
π State
currentSectionsectionOffsets
β οΈ Edge Cases
- Variable heights
- Dynamic data
π Performance
- Avoid recalculating on every scroll
π Architecture
- Intersection observer + fallback measurement
π Approach
- Measure section offsets in
useLayoutEffect - Track scroll position
5. Auto-Resizing Textarea (With Max Height + Scroll)
π Requirements
- Textarea grows with content
- Stops at max height β scrolls
π― Behavior
- No flicker while resizing
β οΈ Edge Cases
- Pasting large content
- Deleting text
π Approach
6. Modal with Focus Trap + Scroll Lock
π Requirements
- Trap focus inside modal
- Prevent background scroll
π― Behavior
- No focus flicker
π Approach
- Focus first element in
useLayoutEffect - Apply
overflow: hiddento body
7. Dynamic Masonry Grid (Pinterest Layout)
π Requirements
- Variable height cards
- Balanced columns
π Approach
- Measure card heights in
useLayoutEffect - Assign to shortest column
8. Scroll Sync Between Two Panels
π Requirements
- Two panels scroll together
β οΈ Edge Cases
- Prevent infinite loop sync
π Approach
- Use flag to prevent recursive updates
- Sync scroll in
useLayoutEffect
9. Responsive Navigation Overflow (More Menu)
π Requirements
- Items overflow into βMoreβ dropdown
π Approach
- Measure container + items width
- Move overflow items dynamically
10. Image Gallery with Aspect Ratio Correction
π Requirements
- Maintain layout before images load
π Approach
- Measure container
- Apply placeholder size using
useLayoutEffect
11. Keyboard Navigation + Auto Scroll Into View
π Requirements
- Arrow keys navigate list
- Active item always visible
π Approach
12. Animated Expand/Collapse (Height Auto Problem)
π Requirements
- Animate
height: 0 β auto
π Approach
- Measure full height in
useLayoutEffect - Animate explicitly
13. Sticky Sidebar with Dynamic Constraints
π Requirements
- Sidebar sticks but stops before footer
π Approach
- Measure container + footer positions
- Adjust
topdynamically
14. Canvas-Based Chart with Resize Awareness
π Requirements
- Chart resizes with container
π Approach
15. Scroll Position Restoration (SPA Navigation)
π Requirements
- Restore scroll on back navigation
π Approach
16. Dynamic Form Step Indicator Alignment
π Requirements
- Progress bar aligns with steps
π Approach
- Measure step positions
- Update progress width
17. Overflow Detection with βRead Moreβ
π Requirements
- Detect if text is truncated
π Approach
18. Drag-to-Resize Table Columns
π Requirements
- Resize columns via drag
β οΈ Edge Cases
- Min/max width
- Table overflow
π Approach
- Update widths via
useLayoutEffect - Sync DOM immediately
19. Floating Action Button (Avoid Overlap with Footer)
π Requirements
- FAB sticks bottom-right
- Moves up when footer visible
π Approach
- Measure footer position
- Adjust FAB offset
π₯ Final Architectural Insight
All these problems test one core idea:Can you control layout before paint while balancing performance?
π§© Senior-Level Thinking
When solving:-
Ask:
- βWill the user see an incorrect frame?β
-
Decide:
useEffectvsuseLayoutEffect
-
Optimize:
- Avoid blocking paint unnecessarily
Below is a senior-level interview set on
useLayoutEffect designed to evaluate deep understanding, decision-making, and real-world debugging ability.
π§ Advanced Interview Questions β useLayoutEffect
1. When would you intentionally choose useLayoutEffect over useEffect, knowing it can hurt performance?
π Follow-up
- What signals tell you this is necessary?
- Can you redesign to avoid it?
β Strong Answer
UseuseLayoutEffect when visual correctness must be guaranteed before paint, such as:
- Measuring DOM (tooltip, popover positioning)
- Preventing layout shift
- Synchronizing scroll/position
βWill the user see a broken frame before correction?βIf yes β
useLayoutEffect.
β Weak Answer
βWhen I need DOM accessββ Fails because both hooks have DOM accessβtiming is the key difference.
2. Explain how useLayoutEffect fits into Reactβs commit phase.
π Follow-up
- What happens if itβs slow?
- Can React interrupt it?
β Strong Answer
Order:- DOM mutations applied
useLayoutEffectruns synchronously- Browser paints
useEffectruns asynchronously
- It blocks paint
- Cannot be interrupted (even in concurrent mode)
β Weak Answer
βIt runs before useEffectββ Too shallowβmisses lifecycle and blocking behavior.
3. You see UI flicker when positioning a dropdown. How do you debug it?
π Follow-up
- How would you confirm itβs a timing issue?
- What tools would you use?
β Strong Answer
Steps:- Identify flicker β suspect post-paint update
- Check if logic is in
useEffect - Move to
useLayoutEffect - Verify using DevTools (paint timing)
β Weak Answer
βAdd delay or debounceββ Treats symptom, not root cause.
4. How can useLayoutEffect cause layout thrashing?
π Follow-up
- How would you fix it in a large component tree?
β Strong Answer
Pattern:- Batch reads first
- Then writes
β Weak Answer
βToo many re-rendersββ Incorrect root cause.
5. What trade-offs exist between useLayoutEffect and CSS solutions?
π Follow-up
- When would you avoid JS entirely?
β Strong Answer
Prefer CSS when:- Static layout (flexbox, grid, vh)
useLayoutEffect when:
- Layout depends on runtime measurement
β Weak Answer
βCSS is fasterββ Oversimplifiedβmisses capability differences.
6. Why is useLayoutEffect problematic in SSR?
π Follow-up
- How do you design isomorphic code?
β Strong Answer
- No DOM/layout on server
- React warns because effect has no meaning
β Weak Answer
βIt doesnβt work on serverββ Lacks explanation and solution.
7. How does useLayoutEffect behave under React Strict Mode?
π Follow-up
- What kind of bugs does this expose?
β Strong Answer
- Runs twice (setup β cleanup β setup)
-
Exposes:
- Non-idempotent logic
- Side effects without cleanup
β Weak Answer
βRuns twice for debuggingββ Doesnβt explain purpose or implications.
8. You have a drag-and-drop system that feels laggy. It uses useLayoutEffect. Whatβs wrong?
π Follow-up
- What would you replace it with?
β Strong Answer
useLayoutEffectblocks paint on every drag update- Causes jank
- Use
useEffect+requestAnimationFrame - Only use layout effect for initial measurement
β Weak Answer
βOptimize code inside effectββ Misses architectural issue.
9. Can useLayoutEffect lead to infinite loops? Explain a real scenario.
π Follow-up
- How would you guard against it?
β Strong Answer
- state update β re-render β effect β update
- Correct dependencies
- Conditional updates
β Weak Answer
βYes, if dependencies are wrongββ Too generic.
10. How would you design a tooltip system at scale (multiple tooltips, portals, dynamic content)?
π Follow-up
- How do you avoid repeated measurements?
β Strong Answer
- Centralized positioning logic (hook/context)
- Measure with
useLayoutEffect - Cache dimensions
- Use portals to avoid layout constraints
β Weak Answer
βUse useLayoutEffect in each tooltipββ Doesnβt scale.
11. What is the relationship between useLayoutEffect and browser paint?
π Follow-up
- How does this impact user perception?
β Strong Answer
- Runs before paint β blocks rendering
- Ensures user sees final layout only
- Better visual stability
- Risk of slower UI
β Weak Answer
βIt runs before renderββ Incorrect.
12. How do you prevent layout shift when loading dynamic content?
π Follow-up
- Would you always use
useLayoutEffect?
β Strong Answer
Options:- Reserve space (CSS)
- Use placeholders
- Measure and adjust with
useLayoutEffectif needed
β Weak Answer
βUse useLayoutEffectββ Over-reliance on JS.
13. When measuring DOM, why is useLayoutEffect preferred over useEffect?
π Follow-up
- What happens if you donβt?
β Strong Answer
- Measurement must reflect final DOM before paint
useEffectcauses visible mismatch β flicker
β Weak Answer
βBecause it runs earlierββ Not enough reasoning.
14. How does useLayoutEffect behave with concurrent rendering?
π Follow-up
- Does it benefit from concurrency?
β Strong Answer
- Still synchronous in commit phase
- Not interruptible
- Doesnβt benefit from concurrent rendering
β Weak Answer
βIt becomes asyncββ Incorrect.
15. How would you debug a performance issue caused by layout effects?
π Follow-up
- What metrics/tools?
β Strong Answer
- Chrome Performance tab
- Look for long tasks before paint
- Identify heavy layout effects
- Move non-critical work to
useEffect
β Weak Answer
βOptimize codeββ Too vague.
16. Why is batching state updates important inside useLayoutEffect?
π Follow-up
- What happens if you donβt?
β Strong Answer
- Multiple
setStateβ multiple renders - Even worse since it blocks paint
- Combine into single update
β Weak Answer
βFor performanceββ Missing mechanism.
17. What mental model do you use for deciding between hooks?
π Follow-up
- Give real-world examples
β Strong Answer
useEffectβ side effects after paintuseLayoutEffectβ layout-critical sync work
βDoes this affect what the user sees immediately?β
β Weak Answer
βDepends on use caseββ Too vague.
18. Can useLayoutEffect replace all useEffect usage? Why or why not?
π Follow-up
- What happens if you try?
β Strong Answer
-
Technically yes, but:
- Blocks paint
- Hurts performance
- Misuses lifecycle
β Weak Answer
βNo, because React says soββ No reasoning.
19. How would you implement scroll restoration correctly?
π Follow-up
- Why not
useEffect?
β Strong Answer
- Must happen before paint to avoid visible jump
β Weak Answer
βUse useEffectββ Causes flicker.
20. What are signs that a developer is misusing useLayoutEffect?
π Follow-up
- How would you refactor their code?
β Strong Answer
-
Used for:
- API calls
- Logging
- Non-visual logic
- Move to
useEffect - Keep layout effects minimal
β Weak Answer
βToo many layout effectsββ Doesnβt identify misuse.
π₯ Final Evaluation Insight
These questions help identify if a candidate:- Understands render β commit β paint pipeline
- Can make trade-off decisions
- Thinks in terms of user perception (not just code)
- Can debug real UI issues