React · Middle · Question 51 of 75

What is wrong with this effect?

const [filtered, setFiltered] = useState([]);
useEffect(() => {
  setFiltered(items.filter((i) => i.visible));
}, [items]);

Explanation

The effect renders once with stale filtered, then again with the new value. const filtered = items.filter(...) (with useMemo if expensive) is always in sync.

Further reading

Problem with a question

React · Middle · question 51

Test yourself

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

Take this quiz