React Hooks useState Hook 2 — Questions and Answers
Question 1: Can you store objects in useState?
- No, only primitives are allowed
- Yes, and React merges them automatically
- Yes, but you must spread the previous state manually (Correct answer)
- No, use useRef instead
Correct answer: Yes, but you must spread the previous state manually
useState does not merge objects like setState in class components; you must spread the old state yourself.
Question 2: What is the correct way to update one property of an object stored in state?
- setUser(user.name = 'Alice')
- setUser({name: 'Alice'})
- setUser({...user, name: 'Alice'}) (Correct answer)
- user.name = 'Alice'; setUser(user)
Correct answer: setUser({...user, name: 'Alice'})
Spreading the previous state and overriding the changed property ensures immutability.
Question 3: How should you add an item to an array stored in useState?
- items.push(newItem); setItems(items)
- setItems([...items, newItem]) (Correct answer)
- setItems(items.concat)
- setItems(items + newItem)
Correct answer: setItems([...items, newItem])
Spreading the existing array into a new array maintains immutability required by React.
Question 4: When does React batch multiple useState setter calls?
- Never
- Only inside event handlers in React 17 and earlier
- In React 18+ batching occurs in all contexts by default (Correct answer)
- Only inside useEffect
Correct answer: In React 18+ batching occurs in all contexts by default
React 18 introduced automatic batching for all contexts including promises, timeouts, and native events.
Question 5: What value does useState return before the setter is ever called?
- undefined
- null
- The initial value passed to useState (Correct answer)
- An empty object
Correct answer: The initial value passed to useState
Before any setter call, the state holds whatever value (or result of function) was passed as the initializer.
Question 6: Which pattern allows you to reset state back to its initial value cleanly?
- Call useState again
- Change the component's key prop (Correct answer)
- Call setCount(useState(0))
- Use useEffect to reset
Correct answer: Change the component's key prop
Changing a component's key prop forces React to unmount and remount it, resetting all internal state.
Can you store objects in useState?