React Hooks useState Hook 1 — Questions and Answers
Question 1: What does the useState hook return?
- A single value
- An array with a state value and a setter function (Correct answer)
- An object with get and set methods
- A Promise
Correct answer: An array with a state value and a setter function
useState returns a tuple of [currentValue, setterFunction] that you destructure.
Question 2: What is the initial value passed to useState used for?
- It is re-evaluated on every render
- It sets the state only on the first render (Correct answer)
- It overrides state on every render
- It is ignored after the component mounts
Correct answer: It sets the state only on the first render
The initial value is only used during the first render; subsequent renders use the current state.
Question 3: Which of the following correctly initializes a counter state to 0?
- const count = useState(0)
- const [count] = useState(0)
- const [count, setCount] = useState(0) (Correct answer)
- const {count, setCount} = useState(0)
Correct answer: const [count, setCount] = useState(0)
Array destructuring with both the state variable and its setter is the correct pattern.
Question 4: What happens if you call the setter function returned by useState with the same value as the current state?
- React always re-renders
- React bails out of the re-render (Correct answer)
- React throws an error
- React resets to the initial value
Correct answer: React bails out of the re-render
React uses Object.is comparison; if the value hasn't changed, it bails out of re-rendering.
Question 5: How do you update state based on the previous state value?
- setCount(count + 1)
- setCount(prev => prev + 1) (Correct answer)
- setCount(this.state.count + 1)
- setCount(useState.prev + 1)
Correct answer: setCount(prev => prev + 1)
Using a functional update (prev => prev + 1) ensures you always operate on the most recent state.
Question 6: Which of these is a valid way to lazily initialize state?
- useState(expensiveComputation)
- useState(() => expensiveComputation()) (Correct answer)
- useState.lazy(expensiveComputation)
- useLazyState(expensiveComputation)
Correct answer: useState(() => expensiveComputation())
Passing a function to useState causes it to run only on the initial render, avoiding repeated expensive calls.
What does the useState hook return?