React State Management 2 — Questions and Answers
Question 1: When you call the state setter from useState, what does React do to the component?
- Schedules a re-render of the component (Correct answer)
- Mutates the existing state object in place
- Forces an immediate synchronous DOM update
- Reloads the entire page
Correct answer: Schedules a re-render of the component
Calling a setter schedules a re-render with the new state value.
Question 2: Which is the correct way to update state that depends on the previous state?
- setCount(count + 1) directly
- setCount(prev => prev + 1) (Correct answer)
- count = count + 1
- setCount(this.count + 1)
Correct answer: setCount(prev => prev + 1)
Passing an updater function guarantees you act on the latest state.
Question 3: Why should you never mutate state arrays directly with push() in React?
- push is deprecated in JavaScript
- React won't detect the change and may not re-render (Correct answer)
- Arrays cannot hold state
- It causes infinite loops always
Correct answer: React won't detect the change and may not re-render
React relies on a new reference to detect changes, so you must create a new array.
Question 4: What is the initial value of state declared as useState()?
- 0
- null
- undefined (Correct answer)
- An empty string
Correct answer: undefined
With no argument, the initial state is undefined.
Question 5: Which hook is best suited for managing complex state logic with multiple sub-values?
- useReducer (Correct answer)
- useState
- useEffect
- useRef
Correct answer: useReducer
useReducer centralizes complex state transitions in a reducer function.
Question 6: What does passing a function to useState's initial argument (lazy initialization) accomplish?
- Runs the function on every render
- Computes the initial state only once on mount (Correct answer)
- Disables state updates
- Memoizes the component
Correct answer: Computes the initial state only once on mount
Lazy initialization runs the function once to compute the initial state.
Question 7: After calling a state setter, is the local state variable updated immediately in the same function scope?
- Yes, instantly
- No, it reflects the new value only on the next render (Correct answer)
- Only in class components
- Only with async/await
Correct answer: No, it reflects the new value only on the next render
State variables are snapshots; the new value appears on the next render.
When you call the state setter from useState, what does React do to the component?