-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathuseEffect-vs-useLayoutEffect.js
More file actions
61 lines (53 loc) · 1.68 KB
/
useEffect-vs-useLayoutEffect.js
File metadata and controls
61 lines (53 loc) · 1.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/**
* 🧠 Concept: useEffect vs useLayoutEffect
*
* ------------------------------------------------------------
* 🧾 Why?
* - React provides two side-effect hooks: `useEffect` and `useLayoutEffect`.
* - Both are used to run code after a component renders, but they behave differently.
*
* ✅ Goal: Understand their timing, usage, and differences with visual clarity.
*/
import React, { useEffect, useLayoutEffect, useRef } from "react";
/**
* 📘 Summary:
* - `useEffect`: Runs **after** paint (async), won't block UI rendering.
* - `useLayoutEffect`: Runs **before** paint (sync), can block UI rendering.
*/
/**
* 🧪 Example Component: useEffect vs useLayoutEffect Demo
*/
function LayoutEffectDemo() {
const effectRef = useRef(null);
const layoutRef = useRef(null);
useEffect(() => {
effectRef.current.style.color = "blue";
effectRef.current.textContent = "👀 useEffect - after paint";
}, []);
useLayoutEffect(() => {
layoutRef.current.style.color = "red";
layoutRef.current.textContent = "🚀 useLayoutEffect - before paint";
}, []);
return (
<div style={{ padding: "1rem", fontFamily: "sans-serif" }}>
<h2>🔍 useEffect vs useLayoutEffect</h2>
<p ref={layoutRef}>⏳ Initial layoutRef text</p>
<p ref={effectRef}>⏳ Initial effectRef text</p>
</div>
);
}
/**
* 🧵 Summary:
*
* 🔁 useEffect:
* - Non-blocking: Runs after paint.
* - Good for API calls, analytics, subscriptions.
*
* ⏱ useLayoutEffect:
* - Blocking: Runs before paint.
* - Best for measuring DOM, animations, syncing layout.
*
* 🚨 Warning:
* - Overusing `useLayoutEffect` can lead to performance issues.
*/
export { LayoutEffectDemo };