React · Middle · Question 53 of 75

Why does this chat effect reconnect when the theme changes?

useEffect(() => {
  const conn = connect(roomId);
  conn.on("connected", () => showToast("Connected", theme));
  return () => conn.disconnect();
}, [roomId, theme]);

Explanation

Every reactive value used in an effect must be listed. useEffectEvent lets the handler read the latest theme without making the effect depend on it.

Further reading

Problem with a question

React · Middle · question 53

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