React · Middle · Question 12 of 75

Why does this effect run after every render?

const options = { roomId, serverUrl };

useEffect(() => {
  const conn = connect(options);
  return () => conn.close();
}, [options]);

Explanation

Dependencies are compared via Object.is, and a new object literal never equals the previous one. The right way is to create the object inside the effect and depend on primitives: [roomId, serverUrl]. Suppressing the linter is a bad idea.

Further reading

Problem with a question

React · Middle · question 12

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