useState Hook
0/3 in this phase0/36 across the roadmap
📖 Concept
State is data that changes over time and affects what is rendered on the screen. The useState hook is the primary way to add state to a functional component.
The Hook Signature:
const [state, setState] = useState(initialValue);
state: The current value of the state.setState: A function to update the state.initialValue: The value the state starts with.
Key Concepts:
- Asynchronous Updates: Calling
setStatedoesn't change the state immediately. It schedules a re-render. - Functional Updates: If your new state depends on the previous state, always use a function:
setCount(prev => prev + 1). - Batching: React batches multiple state updates together into a single re-render for performance.
- Immutability: Never modify state directly (e.g.,
state.name = 'Bob'). Always provide a new object or value.
💻 Code Example
code
1import React, { useState } from 'react';23function ProfileForm() {4 // 1. Initializing state with an object5 const [user, setUser] = useState({6 firstName: '',7 lastName: '',8 email: '',9 isSubscribed: false10 });1112 const handleChange = (e) => {13 const { name, value, type, checked } = e.target;1415 // 2. IMPORTANT: Spread the existing state!16 // Never do: user[name] = value;17 setUser(prevUser => ({18 ...prevUser,19 [name]: type === 'checkbox' ? checked : value20 }));21 };2223 const resetForm = () => {24 // 3. Resetting to initial state25 setUser({26 firstName: '',27 lastName: '',28 email: '',29 isSubscribed: false30 });31 };3233 return (34 <div className="p-6 bg-gray-50 rounded-lg shadow-md max-w-md mx-auto">35 <h2 className="text-xl font-bold mb-4">Update Profile</h2>3637 <div className="space-y-4">38 <input39 name="firstName"40 value={user.firstName}41 onChange={handleChange}42 placeholder="First Name"43 className="w-full p-2 border rounded"44 />45 <input46 name="lastName"47 value={user.lastName}48 onChange={handleChange}49 placeholder="Last Name"50 className="w-full p-2 border rounded"51 />52 <label className="flex items-center space-x-2">53 <input54 type="checkbox"55 name="isSubscribed"56 checked={user.isSubscribed}57 onChange={handleChange}58 />59 <span>Subscribe to newsletter</span>60 </label>6162 <div className="pt-4 border-t flex space-x-2">63 <button className="bg-blue-600 text-white px-4 py-2 rounded">Save</button>64 <button onClick={resetForm} className="bg-gray-300 px-4 py-2 rounded">Reset</button>65 </div>66 </div>6768 <div className="mt-6 p-3 bg-blue-100 rounded text-sm font-mono">69 {JSON.stringify(user, null, 2)}70 </div>71 </div>72 );73}7475export default ProfileForm;
🏋️ Practice Exercise
- Build a 'Counter' with increment, decrement, and reset buttons.
- Create a 'Toggle' component that switches between 'Dark' and 'Light' mode.
- Build a 'To-Do' list where users can add items and mark them as completed.
- Create a component with two counters and a 'Total' display. Update them and notice when the component re-renders.
⚠️ Common Mistakes
Directly mutating state (e.g., state.push(newItem)).
Assuming state is updated immediately after calling the setter.
Not using the functional update pattern when the new state depends on the old state.
Initializing state with props and expecting the state to update when props change (use useEffect or a key for that).
💼 Interview Questions
🎤 Mock Interview
Practice a live interview for useState Hook
Was this topic helpful?