Cơ BảnReact iconReact

useState hook hoạt động như thế nào?

useState nhận giá trị khởi tạo và trả về mảng gồm state hiện tại và setter function.

  • Khi gọi setter, React schedule re-render với giá trị mới.
  • Setter có thể nhận giá trị mới trực tiếp hoặc updater function để tránh stale closure.
tsx
const Counter = () => {
  const [count, setCount] = useState(0)

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>+1 trực tiếp</button>
      <button onClick={() => setCount(prev => prev + 1)}>+1 updater</button>
    </div>
  )
}

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

Mở danh sách React