Lessons in this course (17)

2. State with useState and event handling

Basic★ Must knowLesson 2 of 17
jsx
import { useState } from "react";

function Counter() {
  const [count, setCount] = useState(0);
  const [form, setForm] = useState({ name: "", email: "" });

  return (
    <>
      <button onClick={() => setCount(c => c + 1)}>Clicked {count} times</button>   {/* functional update */}
      <input
        value={form.name}
        onChange={e => setForm(prev => ({ ...prev, name: e.target.value }))}    // immutable update
      />
    </>
  );
}
  • State updates are asynchronous and batched — count doesn't change until the next render. Use the functional form (c => c + 1) when the new value depends on the old one.
  • Never mutate state (form.name = "x"); create new objects/arrays ([...items, newItem], items.filter(...), items.map(...)).
  • Lazy initial state for expensive computation: useState(() => loadFromStorage()).
  • Events are React synthetic events wrapping native ones; e.preventDefault() for forms.