Gaëtan GR
Gaëtan GR

Reputation: 1398

Infinite rerendering with useEffect

I'm trying to rerender a component once the state is changed, this how I do it:

const [items, setItems] = useState([]);

useEffect(() => {
    console.log("I am rerendering")
    const displayNotebook = async () => {
    const reponse = await axios({// URL etc...},
      });
      setItems(reponse.data); // add data to the list
    };

   displayNotebook()
  
  },[items]);

I pass the date in a map as so

const workspaceCard = items.map((msg) => (
<WorkspaceContent
  message={msg.content}
/>));

The problem is that the component is in a infinite rerendering, I could use an empty array but this not what I want, I am trying to rerender the component each time the state is updated.

I searched and found this answer Infinite loop in useEffect but does not help me

Upvotes: 0

Views: 51

Answers (1)

Christian Fritz
Christian Fritz

Reputation: 21384

As Gaëtan already indicated, your logic has a loop: inside your effect you are setting items, but you are also indicating that the effect should re-run whenever items change. Hence the cycle. The fix is simple then, just remove the dependency on items, if you don't need/want to rerun the effect whenever they change:

useEffect(() => {
    // ...
  },[]);  // items removed

Upvotes: 1

Related Questions