useState

A React Hook that lets you add state to function components, returning the current state value and a function to update it.

Overview

useState is the most commonly used React Hook. It allows function components to have their own state that persists across re-renders. When you call useState, you get back an array with two elements: the current state value and a function to update it. Updating state triggers a component re-render.

Example

javascript
import { useState } from 'react';

function Counter() {
  // Declare state variable
  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>
  );
}

// Multiple state variables
function Form() {
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');

  return (
    <form>
      <input
        value={name}
        onChange={(e) => setName(e.target.value)}
      />
      <input
        value={email}
        onChange={(e) => setEmail(e.target.value)}
      />
    </form>
  );
}

// Object state
function User() {
  const [user, setUser] = useState({
    name: '',
    age: 0
  });

  const updateName = (name) => {
    setUser({ ...user, name });
  };
}

Key Points

  • Returns array: [state, setState]
  • Initial value can be any type
  • Updating state triggers re-render
  • State updates are asynchronous
  • Use functional update for computed state

Learn More