All jobs / Frontend / web developer / React
Frontend / web developer interview question · 0–1 years
What does useState return, and why must you call the setter instead of assigning?
The strongest answer
A pair: the current value and a setter; React re-renders only when the setter is called, so assigning to the variable changes nothing on screen
Why it works
Right. The setter is how React learns something changed.
What a good answer covers
- const [value, setValue] = useState(initial).
- Assigning the variable does nothing.
- Setter schedules a re-render.
- Functional updates when the next depends on the previous.
Answers that fall short
- Close, but not the strongest: An object with get and set methods
It is an array pair, not an object. - Weak: A promise of the value
It is synchronous in shape; updates are scheduled. - Red flag: The value only
Two items, destructured.
Who gets asked this
More React questions
- Why does React warn about a missing key when you render a list?
- What is a controlled input?
- What is useEffect for?
- What happens if useEffect has an empty dependency array, and if it has none at all?
- How do you render something only when a condition holds?
- Why does onClick={handleClick()} fire during render instead of on click?
- Two sibling components need the same piece of data. Where does it live?
- Why does a component return a fragment instead of a wrapping div?