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:

  1. Asynchronous Updates: Calling setState doesn't change the state immediately. It schedules a re-render.
  2. Functional Updates: If your new state depends on the previous state, always use a function: setCount(prev => prev + 1).
  3. Batching: React batches multiple state updates together into a single re-render for performance.
  4. Immutability: Never modify state directly (e.g., state.name = 'Bob'). Always provide a new object or value.

💻 Code Example

codeTap to expand ⛶
1import React, { useState } from 'react';
2
3function ProfileForm() {
4 // 1. Initializing state with an object
5 const [user, setUser] = useState({
6 firstName: '',
7 lastName: '',
8 email: '',
9 isSubscribed: false
10 });
11
12 const handleChange = (e) => {
13 const { name, value, type, checked } = e.target;
14
15 // 2. IMPORTANT: Spread the existing state!
16 // Never do: user[name] = value;
17 setUser(prevUser => ({
18 ...prevUser,
19 [name]: type === 'checkbox' ? checked : value
20 }));
21 };
22
23 const resetForm = () => {
24 // 3. Resetting to initial state
25 setUser({
26 firstName: '',
27 lastName: '',
28 email: '',
29 isSubscribed: false
30 });
31 };
32
33 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>
36
37 <div className="space-y-4">
38 <input
39 name="firstName"
40 value={user.firstName}
41 onChange={handleChange}
42 placeholder="First Name"
43 className="w-full p-2 border rounded"
44 />
45 <input
46 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 <input
54 type="checkbox"
55 name="isSubscribed"
56 checked={user.isSubscribed}
57 onChange={handleChange}
58 />
59 <span>Subscribe to newsletter</span>
60 </label>
61
62 <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>
67
68 <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}
74
75export default ProfileForm;

🏋️ Practice Exercise

  1. Build a 'Counter' with increment, decrement, and reset buttons.
  2. Create a 'Toggle' component that switches between 'Dark' and 'Light' mode.
  3. Build a 'To-Do' list where users can add items and mark them as completed.
  4. 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