Understanding useState
The Basics
const [value, setValue] = useState(initialValue);
Hooks add state to function components. useState returns: 1. The current state value 2. A function to update that value
Simple Counter
import { useState } from 'react';
export function Counter() { const [count, setCount] = useState(0); return ( <div> <p>Count: {count}</p> <button onClick={() => setCount(count + 1)}>+</button> </div> ) }
Updating State
Direct Update
setCount(5);
Function Update (recommended for prev value)
setCount(prev => prev + 1); setCount(prev => prev + 1); // This queues two updates correctly
Multiple State Variables
const [name, setName] = useState(''); const [age, setAge] = useState(0); const [email, setEmail] = useState('');
Or combine into an object:
const [user, setUser] = useState({ name: '', age: 0, email: '' });
setUser(prev => ({ ...prev, name: 'John' }));
Lazy Initialization
For expensive initial state:
const [state, setState] = useState(() => { // This runs only once return calculateExpensiveValue(); });
This prevents unnecessary computation on every render.