React useState Hook Cheat Sheet

What is `useState`?

A React Hook that lets you add state to functional components.

import { useState } from "react";

Basic Usage

const [count, setCount] = useState(0);
  • count: current state value
  • setCount: function to update the state
  • 0: initial state

Updating State

<button onClick={() => setCount(count + 1)}>
  Increment
</button>

State with Strings

const [name, setName] = useState("Jane");

<input
  type="text"
  value={name}
  onChange={(e) => setName(e.target.value)}
/>

State with Objects

const [user, setUser] = useState({ name: "Jane", age: 30 });

setUser({ ...user, age: 31 });

State with Arrays

const [items, setItems] = useState([]);

setItems([...items, "New Item"]);

Lazy Initialization (for expensive initial state)

const [value, setValue] = useState(() => computeInitialValue());

Functional Updates

Use previous state if new state depends on it:

setCount(prev => prev + 1);

Multiple State Hooks

const [name, setName] = useState("");
const [email, setEmail] = useState("");