Nâng CaoReact iconReact

Lazy initialization của useState là gì và khi nào dùng?

Truyền function vào useState thay vì giá trị trực tiếp: useState(() => computeExpensiveValue()).

  • Function này chỉ chạy một lần khi mount, không chạy lại mỗi render.
  • Hữu ích khi khởi tạo state từ localStorage hay tính toán phức tạp: useState(() => JSON.parse(localStorage.getItem('key'))).

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

Mở danh sách React