|
1 | 1 | --- |
2 | 2 | title: What is the difference between `useEffect` and `useLayoutEffect` in React? |
3 | 3 | --- |
| 4 | +### **TL;DR** |
| 5 | +- **`useEffect`**: Executes **after** the screen is painted. Use for non-blocking side effects (e.g., data fetching, subscriptions). |
| 6 | +- **`useLayoutEffect`**: Executes **before** the screen is painted. Use for DOM measurements or updates requiring precision before rendering. |
| 7 | +- **Key Rule**: Prefer `useEffect` unless precise DOM updates are needed before paint. |
| 8 | + |
| 9 | +--- |
| 10 | + |
| 11 | +### **What is the difference between `useEffect` and `useLayoutEffect` in React?** |
| 12 | + |
| 13 | +1. **Execution Timing**: |
| 14 | + - **`useEffect`**: Runs **after** the browser paints the screen. It ensures that side effects do not block the browser's rendering process. |
| 15 | + - **`useLayoutEffect`**: Runs **before** the browser paints, ensuring DOM updates or measurements are complete before rendering is visible to the user. |
| 16 | + |
| 17 | +2. **Use Cases**: |
| 18 | + - **`useEffect`**: |
| 19 | + - Fetching data from APIs. |
| 20 | + - Setting up event listeners, timers, or subscriptions. |
| 21 | + - Logging or analytics. |
| 22 | + - **`useLayoutEffect`**: |
| 23 | + - Measuring DOM elements (e.g., width, height). |
| 24 | + - Synchronizing animations with DOM updates. |
| 25 | + - Applying immediate DOM styles or modifications. |
| 26 | + |
| 27 | +3. **Performance Impact**: |
| 28 | + - **`useEffect`**: Non-blocking, does not delay rendering, making it more performance-friendly for most scenarios. |
| 29 | + - **`useLayoutEffect`**: Can block rendering and should be used sparingly to avoid performance bottlenecks. |
| 30 | + |
| 31 | +4. **Common Rule**: |
| 32 | + - Use **`useEffect`** for most cases. |
| 33 | + - Use **`useLayoutEffect`** only when precise DOM operations must occur before rendering. |
| 34 | + |
| 35 | +--- |
| 36 | + |
| 37 | +### **Example Code** |
| 38 | + |
| 39 | +```jsx |
| 40 | +import React, { useEffect, useLayoutEffect, useRef } from 'react'; |
| 41 | + |
| 42 | +function Example() { |
| 43 | + const ref = useRef(); |
| 44 | + |
| 45 | + useEffect(() => { |
| 46 | + console.log('useEffect: DOM is painted'); |
| 47 | + }); |
| 48 | + |
| 49 | + useLayoutEffect(() => { |
| 50 | + console.log('useLayoutEffect: Before paint'); |
| 51 | + ref.current.style.color = 'red'; // Immediate DOM update |
| 52 | + }); |
| 53 | + |
| 54 | + return <div ref={ref}>Hello, World!</div>; |
| 55 | +} |
| 56 | +``` |
| 57 | + |
| 58 | +--- |
0 commit comments