How to manage local state with useState in React

· Category: React

Short answer

useState is a React Hook that lets functional components hold and update local state. It returns the current state value and a setter function.

Steps

  1. Import useState from React.
  2. Call it with an initial value: const [count, setCount] = useState(0).
  3. Read the state directly.
  4. Update it with the setter, using a functional updater when the new state depends on the previous state.

Example

import { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>{count}</p>
      <button onClick={() => setCount((c) => c + 1)}>+</button>
    </div>
  );
}

Common issues

  • State updates are batched and asynchronous; do not read count immediately after setCount and expect it to reflect the new value.
  • Objects and arrays must be replaced, not mutated. Use the spread operator or a library like Immer.