React · Senior · Question 29 of 75
When is it acceptable to call setState directly during render?
- ✓Correct answer: To adjust state when a prop changes, with a guard condition against loops
- 2Never: it always causes a "Too many re-renders" error
- 3Always, whenever you need to sync any state with new props
Explanation
The "storing information from previous renders" pattern: if (items !== prevItems) { setPrevItems(items); setSelection(null); }. React immediately re-runs the component's render without painting the intermediate state. It's better than useEffect, but key or computing during render is even better.