Code Reference

useState

React · Reference cheat sheet

useState

React · Reference cheat sheet


📋 Overview

useState adds local state to a function component. Calling the setter queues a re-render with the new value.

🔧 Core concepts

  • Signatureconst [state, setState] = useState(initial).
  • Lazy inituseState(() => expensive()) runs once.
  • Updater formsetState(prev => next) when next depends on previous.
  • Objects/arrays — replace immutably; don’t mutate then set the same reference.
  • Batching — React batches updates in event handlers (and more in React 18+).

💡 Examples

import { useState } from "react";

export function Counter() {
  const [count, setCount] = useState(0);
  return (
    <button type="button" onClick={() => setCount((c) => c + 1)}>
      {count}
    </button>
  );
}
type Todo = { id: string; text: string; done: boolean };

export function TodoDraft() {
  const [todos, setTodos] = useState<Todo[]>([]);

  function add(text: string) {
    setTodos((prev) => [
      ...prev,
      { id: crypto.randomUUID(), text, done: false },
    ]);
  }

  function toggle(id: string) {
    setTodos((prev) =>
      prev.map((t) => (t.id === id ? { ...t, done: !t.done } : t)),
    );
  }

  return null; // wire UI as needed
}

⚠️ Pitfalls

  • setState(obj.x++) / mutating then setState(obj) — React may skip the update.
  • Using state as the only source when you could derive: const full = first + last.
  • Storing props in state without a sync strategy → stale UI.
  • For complex transitions prefer useReducer.

On this page