dosebot
dosebot

Reputation: 121

Setting a react hook to an array causing loop

Has anyone else noticed this weird behavior?

It seems that when i declare a function that sets a hook to an array within the useState hook, I get a infinite loop.

But setting the same hook to an empty string does not cause a loop.

import React, { useState, useEffect } from "react";
import "./App.css";

function App() {
  const [foo, setFoo] = useState([]);
  

  useEffect(() => {
    console.log("useEffect")
    FooFunction()
  },[foo]);

  function FooFunction () {
    // If you setFoo with an array we can an infinite loop
    setFoo('')
    // setFoo([1,2,3])
  }

  return <div className="App">Whats up with this loop?</div>;
}

export default App;

Upvotes: 2

Views: 238

Answers (1)

Todd Skelton
Todd Skelton

Reputation: 7239

Arrays are reference types. By setting foo to an array, you are creating a new reference. That means your dependency on foo in your useEffect changes. Any changes in your dependencies trigger a rerender of your component.

When you use setFoo(''), strings are compared by value (e.g. '' === '' is true) so your dependency doesn't change in that case.

Upvotes: 7

Related Questions