0

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

skyboyer
  • 22,209
  • 7
  • 57
  • 64
Gaëtan GR
  • 1,380
  • 1
  • 5
  • 21
  • 3
    You need to revise your logic, you are triggering an effect to update items whenever items get updated – apokryfos Feb 02 '21 at 21:26

1 Answers1

1

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
Christian Fritz
  • 20,641
  • 3
  • 42
  • 71