Reputation: 1398
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
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