react useEffect is running and fetching data none stop

Viewed 1490

I have a simple react component that uses react hooks. I'm using useEffect and useState.
The problem is that i realized my API is getting huge amount of hits, after debugging i see that useEffect is running none stop!

This is my very simple code:

function DisplayUser({userId}) {
  const [loggedUser, setLoggedUser] = React.useState(null);
  React.useEffect(() => {
    fetchData(userId).then(user => {
      setLoggedUser(user);
    })
  });
  return (
    <div>
      <div>{loggedUser}</div>
    </div>
  );
}
1 Answers

Whats happening here is that useEffect is running after each render

Does useEffect run after every render? Yes! By default, it runs both after the first render and after every update...

There is a way to do Optimizing Performance by Skipping Effects, you can pass an array as a second argument.

If the array is empty, that means there are no "dependencies" for this effect and it will run only once (quite simillar to componentDidMount).

If the array has values, then the effect will re-run only when those values have changeded (simillar to what we do with componentDidUpdate).

So in your case it is wise to pass an array with the userId value because you'll want to re-run the effect and fetch the user data only when the userId has changed.

function DisplayUser({userId}) {
  const [loggedUser, setLoggedUser] = React.useState(null);
  React.useEffect(() => {
    fetchData(userId).then(user => {
      setLoggedUser(user);
    })
  }, [userId]); // only run when userId changed
  return (
    <div>
      <div>{loggedUser}</div>
    </div>
  );
}
Related