React HooksEasy
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:
- The current state: The value as it exists in the current render cycle.
- 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';23export default function UserProfile() {4 // Basic primitive state5 const [isEditing, setIsEditing] = useState(false);67 // Object state - remember to spread previous state!8 const [user, setUser] = useState({9 name: 'Jane Doe',10 role: 'Developer',11 age: 2812 });1314 // Lazy initialization for expensive calculations15 const [complexData, setComplexData] = useState(() => {16 // This only runs on the very first render17 return Array.from({ length: 1000 }, (_, i) => i);18 });1920 const handleUpdateAge = () => {21 // ✅ Correct: Using functional update and spreading old state22 setUser(prevUser => ({23 ...prevUser,24 age: prevUser.age + 125 }));26 };2728 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>3132 <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>3637 <button38 onClick={handleUpdateAge}39 className="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-colors"40 >41 Celebrate Birthday42 </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.