0

I have this basic useEffect

const [dummy, setDummy] = useState('a');
  const [bubble, setBubble] = useState([]);
  useEffect(() => {
    console.log('useEffect in Context');
    setDummy('z');
    console.log(dummy);
  }, [dummy]);

the useEffect is called when the app is started, it logs 'a' (correct) then is executed again (as the dependency called 'dummy' changed) and logs 'z' (still correct) and everything stops there

but if i change dummy with bubble (an array) and use bubble as dependency:

const [dummy, setDummy] = useState('a');
  const [bubble, setBubble] = useState([]);
  useEffect(() => {
    console.log('useEffect in Context');
    setDummy('z');
    setBubble(['Context']);
    console.log(bubble);
  }, [bubble]);

the app start looping, first time it logs an empty array (right, it was init as empty) then it logs ['Context'] and then starts looping still logging ['Context'] it looks like array are always differnet even if equal!

what am i missing?

popeating
  • 386
  • 1
  • 2
  • 16
  • 1
    `useEffect` tests for strict equality in its dependency array. Type this into an editor somewhere - `console.log(['a'] === ['a'])` - it will print false because two independently generated arrays are never strictly equal, even if they share the same elements. – lawrence-witt Nov 26 '20 at 20:41
  • 1
    "it looks like array are always differnet even if equal!" - you're creating a new array every time and setting it `['Context'] !== ['Context']` – Matt Aft Nov 26 '20 at 20:41
  • That's what I was missing, now it makes sense! thank you – popeating Nov 26 '20 at 20:53

0 Answers0