useEffect and useLayoutEffect are two hooks for executing side effects. The difference is when they execute.
Simple analogy: Imagine you are a photographer at a wedding.
Technically:
useEffect (asynchronously — after rendering):
useLayoutEffect (synchronously — before rendering):
1// Example: need to know element height2function MyComponent() {3 const ref = useRef();45 // useLayoutEffect — BEFORE the user sees6 useLayoutEffect(() => {7 console.log('Height:', ref.current.offsetHeight);8 }, []);910 return <div ref={ref}>...</div>;11}
Step-by-step comparison:
When useLayoutEffect is necessary:
Common mistake: Using useLayoutEffect for data fetching. This blocks the browser and causes poor performance. Always use useEffect for async operations like API calls.
Rule: Always start with useEffect. If you see "flicker" or need to measure DOM before rendering — use useLayoutEffect.