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'))).
Pass a function to useState instead of a direct value: useState(() => computeExpensiveValue()).
- This initializer function runs only once on mount, not on every re-render.
- Use it when the initial state requires an expensive computation or a side effect like reading from localStorage:
useState(() => JSON.parse(localStorage.getItem('key'))).