Khi một component được render lần đầu trong React, thứ tự thực thi của useState và useEffect diễn ra như sau:
Published on February 26, 2025
react
Khi một component được render lần đầu trong React, thứ tự thực thi của useState
và useEffect
diễn ra như sau:
🔥 Thứ tự thực thi khi component mount (lần đầu render):
Khởi tạo component
React gọi hàm component để bắt đầu quá trình render.
Chạy
useState
(khởi tạo state)useState
được thực thi trong quá trình render, nhưng giá trị của state chỉ được khởi tạo lần đầu.Nếu bạn có
useState(null)
, nó sẽ giữ giá trịnull
cho đến khi được cập nhật.
Render JSX & Kết xuất giao diện (
return
của component)React render UI dựa trên state và props.
Chạy
useEffect
có[]
(chỉ chạy một lần sau render đầu tiên - componentDidMount behavior)Sau khi giao diện đã được render lên UI, React chạy
useEffect
với dependency array[]
.Đây là nơi bạn gọi API hoặc thao tác với DOM.
💡 Minh họa cụ thể với code
const MyComponent = () => {
console.log("1️⃣ Component function chạy");
const [count, setCount] = useState(0);
console.log("2️⃣ useState chạy: count =", count);
useEffect(() => {
console.log("4️⃣ useEffect chạy (componentDidMount)");
}, []);
return <div>Count: {count}</div>;
};
🔥 Kết quả log khi component mount:
1️⃣ Component function chạy
2️⃣ useState chạy: count = 0
4️⃣ useEffect chạy (componentDidMount)
🔄 Thứ tự chạy khi component re-render
Nếu component re-render do cập nhật state hoặc props:
Gọi lại hàm component →
useState
giữ nguyên giá trị cũ.Render lại JSX.
Chạy
useEffect
nếu dependencies thay đổi.
Ví dụ:
useEffect(() => {
console.log("useEffect chạy khi count thay đổi:", count);
}, [count]);
Khi count
thay đổi, useEffect
chạy lại.
🎯 Tổng kết thứ tự
React gọi hàm component (hàm render).
useState
được thực thi (giữ giá trị cũ nếu có re-render).JSX được render ra UI.
Sau khi render,
useEffect
chạy (nếu có).
⏳ useEffect(() => {...}, [])
chạy sau lần render đầu tiên (tương đương componentDidMount
).
Related Articles
How to Improve Your Blog Design
Learn tips and tricks to enhance your blog's appearance and usability.
Top Blogging Tools in 2024
Discover the best tools to elevate your blogging experience.
Writing Content that Converts
Learn the art of creating engaging and effective blog content.