React · Senior · Question 29 of 75

When is it acceptable to call setState directly during render?

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.

Further reading

Problem with a question

React · Senior · question 29

Test yourself

Take the React · Senior quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz