useState is a React hook that creates a state variable and a function to update it.
The initialValue sets what the state starts as when the component loads.
Examples
This creates a number state called count starting at 0.
React
const [count, setCount] = useState(0);
This creates a text state called name starting empty.
React
const [name, setName] = useState('');
This creates a true/false state called isVisible starting as true.
React
const [isVisible, setIsVisible] = useState(true);
Sample Program
This React component shows a button and a number. Each time you click the button, the number increases by one. The number is stored in state so React remembers it and updates the screen.
B. Directly modifying state variable instead of using setter
C. Using const instead of let for count
D. Setter function name is incorrect
Solution
Step 1: Identify how state should be updated
React state must be updated using the setter function returned by useState, not by direct assignment.
Step 2: Analyze the code's mistake
The code tries to assign directly to count, which is a constant and does not update React state.
Final Answer:
Directly modifying state variable instead of using setter -> Option B
Quick Check:
Use setter function to update state [OK]
Hint: Never assign state variable directly; use setter function [OK]
Common Mistakes:
Trying to assign value directly to state variable
Ignoring that useState returns a setter function
Confusing const with let for state variables
5. You want to create a React component that shows a list of items and lets the user add new items. Which approach correctly uses state to update the list when a new item is added?
hard
A. Use const [items, setItems] = useState([]); and update with setItems([...items, newItem])
B. Use let items = []; and push new items with items.push(newItem)
C. Use const items = []; and reassign with items = items.concat(newItem)
D. Use const [items, setItems] = useState([]); and update with items.push(newItem)
Solution
Step 1: Understand state immutability in React
State should not be mutated directly; instead, create a new array with the new item added.
Step 2: Check each option's update method
Use const [items, setItems] = useState([]); and update with setItems([...items, newItem]) uses spread syntax to create a new array and calls setter, which is correct. Options A and D mutate the array directly. Use const items = []; and reassign with items = items.concat(newItem) tries to reassign a const variable.
Final Answer:
Use const [items, setItems] = useState([]); and update with setItems([...items, newItem]) -> Option A
Quick Check:
Update state immutably with setter [OK]
Hint: Always create new array and use setter to update state [OK]
Common Mistakes:
Mutating state array directly with push
Reassigning const variables
Not using setter function to update state
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.