Trung BìnhReact iconReact

Stale closure trong useEffect là gì và cách tránh?

Stale closure xảy ra khi effect capture giá trị cũ của state hoặc props vì closure bị tạo lúc render trước.

Giải pháp: thêm dependencies bị thiếu vào array, dùng useRef để lưu giá trị mới nhất không cần re-run effect, hoặc dùng functional updater setState(prev => ...) để không cần reference state trong closure.

Xem toàn bộ React cùng filter theo level & chủ đề con.

Mở danh sách React