score:1

Accepted answer

It's better to make api call only once the component get mounted:

useEffect(() => {
  getTournaments(props.sport)
}, [props.sport]}

score:2

You're almost there, you're doing the correct use of the useState hook, but you need to wrap your function in an useEffect hook, because you're. performing a side effect.

useEffect(() => {
  const getTournaments = async (sport) => {
   axios
   .get("https://futbol-back.herokuapp.com/tournaments/sport/" + sport)
   .then(function(response) {
    // handle success
    // tournaments = response.data;
    if (props.sport!= selected_sport){ // This is where I correct the infinite loop
      console.log(selected_sport)
      selected_sport = props.sport
      setTournaments(response.data)

    }
  })
  .catch(function(error) {
    // handle error
    console.log(error);
  })
  .then(function() {
    // always executed
  });
};

 getTournaments(props.sport);
}, []);

This will assure that your effect will run when the component mounts and it will only run once. All your side effects should go in the use effect


Related Query

More Query from same tag