Core Concepts

State with useState

Use the useState hook to add dynamic, interactive behavior to your React components.

What is State?

State is data that changes over time in a component. When state changes, React automatically re-renders the component to reflect the new data.

useState Hook

The useState hook lets you add state to function components. It returns an array with two items:

  1. The current state value
  2. A function to update that value

Rules of useState

  • Only call hooks at the top level of your component (not inside loops or conditions)
  • Only call hooks from React function components or custom hooks

State Updates are Asynchronous

React batches state updates for performance. Never rely on the current state value to calculate the next state — use the functional update form instead.

Example

jsx
import { useState } from 'react';

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

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
      <button onClick={() => setCount(count - 1)}>Decrement</button>
      <button onClick={() => setCount(0)}>Reset</button>
    </div>
  );
}

// State with objects
function Form() {
  const [form, setForm] = useState({ name: '', email: '' });

  const handleChange = (e) => {
    setForm({ ...form, [e.target.name]: e.target.value });
  };

  return (
    <form>
      <input
        name="name"
        value={form.name}
        onChange={handleChange}
        placeholder="Name"
      />
      <input
        name="email"
        value={form.email}
        onChange={handleChange}
        placeholder="Email"
      />
      <p>Hello, {form.name}!</p>
    </form>
  );
}

// Functional update form (safe for async updates)
function SafeCounter() {
  const [count, setCount] = useState(0);

  const increment = () => setCount(prev => prev + 1);

  return <button onClick={increment}>Count: {count}</button>;
}
Try it yourself — JSX