Skip to content
Advertisement

Why is my component in React being called multiple times?

I am having an issue where my Listings component is running twice and I only want it to run once. I tried adding a counter below that would only run the code that grabs the data from the backend once but that did not work as you can see below it is still looping through the “grabListings” Function twice. I also tried a while loop and same result I am getting two results instead of one.

I believe my issue has to do with the way I am calling the Listings component on my LandingPage.

How can I run the grabListings component only once?

LandingPage

JavaScript

Listings Component

JavaScript

Result enter image description here

Advertisement

Answer

Because React will re-render when state change, if you want stop re-render, put your grabListings() inside useEffect() like this:

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement