Cả hai Hook đều dùng để xử lý side effects, nhưng khác nhau ở thời điểm thực thi:
1. useEffect (Bất đồng bộ - Asynchronous):
- Chạy SAU KHI React đã render UI lên màn hình.
- Trình duyệt không bị block, do đó giao diện hiển thị nhanh hơn.
- Phù hợp cho hầu hết tác vụ như gọi API, tracking, đăng ký event.
2. useLayoutEffect (Đồng bộ - Synchronous):
- Chạy TRƯỚC KHI trình duyệt kịp vẽ (paint) UI mới lên màn hình.
- React sẽ đợi đoạn code trong useLayoutEffect chạy xong hoàn toàn rồi mới cho phép trình duyệt sơn pixel lên màn hình.
- Khi nào dùng: Chỉ dùng khi bạn cần đo đạc DOM (vd: lấy kích thước scroll, width/height của thẻ div) và lập tức thay đổi UI dựa trên kết quả đó trước khi người dùng kịp nhìn thấy. Nếu dùng useEffect trong trường hợp này, giao diện sẽ bị nháy (flicker) vì nó render lần đầu rồi ngay lập tức re-render lại kích thước mới.
Both Hooks handle side effects but differ significantly in their execution timing:
1. useEffect (Asynchronous):
- Runs AFTER React has rendered the UI to the screen (after the paint).
- It does not block the browser, allowing the UI to feel responsive.
- Best for 99% of tasks like fetching data, analytics tracking, or setting up general event listeners.
2. useLayoutEffect (Synchronous):
- Runs synchronously BEFORE the browser paints the new UI to the screen.
- React completely blocks the browser from painting until the code inside useLayoutEffect finishes executing.
- When to use it: Only when you need to read layout from the DOM (e.g., measuring scroll positions, element width/height) and immediately mutate the DOM based on that measurement before the user sees anything. If you use useEffect for this, the user might see a visual flicker as the UI renders the old size, then rapidly re-renders the new size.