What is useState and how does it work?

The useState hook is the most fundamental hook in React. It allows functional components to hold and manage local state, a feature that was previously exclusive to class components.

How it works:

When you call useState(initialValue), it returns an array containing two elements:

  1. The current state: The value as it exists in the current render cycle.
  2. The setter function: A function used to update the state and trigger a component re-render.

Core Concepts:

  • Lazy Initialization: If your initial state requires heavy computation, you can pass a function useState(() => expensiveMath()). This function will only execute once during the initial render.
  • Functional Updates: If your next state depends on the previous state, always pass a callback to the setter setCount(prev => prev + 1). This prevents bugs caused by stale closures.
  • Immutability: Always treat state as immutable. Never mutate objects or arrays directly; instead, create a new copy and pass it to the setter.
  • Batching: React 18 automatically batches multiple consecutive state updates into a single re-render to optimize performance.

Code example

tsx
1import React, { useState } from 'react';
2
3export default function UserProfile() {
4 // Basic primitive state
5 const [isEditing, setIsEditing] = useState(false);
6
7 // Object state - remember to spread previous state!
8 const [user, setUser] = useState({
9 name: 'Jane Doe',
10 role: 'Developer',
11 age: 28
12 });
13
14 // Lazy initialization for expensive calculations
15 const [complexData, setComplexData] = useState(() => {
16 // This only runs on the very first render
17 return Array.from({ length: 1000 }, (_, i) => i);
18 });
19
20 const handleUpdateAge = () => {
21 // ✅ Correct: Using functional update and spreading old state
22 setUser(prevUser => ({
23 ...prevUser,
24 age: prevUser.age + 1
25 }));
26 };
27
28 return (
29 <div className="p-6 border rounded-xl shadow-sm bg-white">
30 <h2 className="text-2xl font-bold mb-4">{user.name}'s Profile</h2>
31
32 <div className="space-y-2 mb-6">
33 <p><span className="font-semibold">Role:</span> {user.role}</p>
34 <p><span className="font-semibold">Age:</span> {user.age}</p>
35 </div>
36
37 <button
38 onClick={handleUpdateAge}
39 className="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-colors"
40 >
41 Celebrate Birthday
42 </button>
43 </div>
44 );
45}

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React Hooks set.

Open in study app