useStateis the most fundamental React Hook. It allows function components to store and update state, making UIs dynamic and interactive.
useState lets a component remember values between renders.
It returns:
const [state, setState] = useState(initialValue)
Clicking the button updates the state and re-renders the UI.
function Counter() {const [count, setCount] = useState(0)return (<button onClick={() => setCount(count + 1)}>{count}</button>)}
When new state depends on previous state. This avoids bugs when updates happen quickly or in batches.
setCount(prev => prev + 1)
Always copy state instead of mutating it:
const [user, setUser] = useState({ name: "Daniel" })setUser(prev => ({ ...prev, name: "Alex" }))
setItems(prev => [...prev, newItem])
For expensive initial state. This runs only once, not on every render.
const [value, setValue] = useState(() => computeInitial())
Rule of thumb: if only one component needs it, keep it local -> fewer unnecessary re-renders.
function SearchInput() {const [query, setQuery] = useState("");return (<inputvalue={query}onChange={(e) => setQuery(e.target.value)}placeholder="Search..."/>);}
Rule of thumb: if multiple components need it, lift it up.
function App() {const [query, setQuery] = useState("");return (<><SearchInput query={query} onChange={setQuery} /><SearchResults query={query} /></>);}