Swapneel
Swapneel

Reputation: 196

UseEffect hook executes multiple times on updating state

I am updating state of parent component from child component's useEffect hook. Follwing is the piece of code from child component. Here useEffect is getting called twice. Not sure how can I avoid it.

useEffect = () => { const flag = someApi; setStateOfParent(flag),[]}

Upvotes: 2

Views: 15550

Answers (3)

Sridhar
Sridhar

Reputation: 431

This below code will fix the issue:

useEffect(() => {
  // executed only once
}, [])

Upvotes: 10

Musadiq Khan
Musadiq Khan

Reputation: 153

You do not set state in useEffect. Make a function to get data from API, call it in useEffect and setState in that function. You can check a an example code below.

useEffect(() => {
  getImage();
}, []); // Calling getImage function to fetch data

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

async function getImage() {
  try {
    const response = await axios.get("https://picsum.photos/v2/list");
    let image = response.data;

    for (var i in image) {
      let x = "https://picsum.photos/id/";
      let y = image[i].id;
      let v = image[i].width;
      image[i].author = `${x}${y}/${v}/${image[i].height}`;
      image[i].height = Math.floor(Math.random() * 650) + 300;
      let z = image[i].height;

      image[i].download_url = `url(${x}${y}/${v}/${z})`;
    }
    set(image); // setting state after fetching data
  } catch (error) {
    console.error(error);
  }
}

Upvotes: -4

Daniel Afonso
Daniel Afonso

Reputation: 81

You should definitely avoid setting state inside useEffect because it will trigger a new render. Also, if you specify your effect dependencies you will have better control over it and assure that it will only get executed when one of those dependencies change.

Upvotes: 2

Related Questions