Banana Boy
Banana Boy

Reputation: 1

Too many re-renders

I get the to many re-renders error

I tried to use useEffect to only render when weater changes

function DashboardHeaderContent({ looks, weather }) {
  const [seasonRange, setSeasonRange] = React.useState();

  function renderLook(look) {
    return <Look id={look._id} img={look.img} title={look.title} />;
  }

  if (weather.temp >= 7 && weather.temp <= 16) {
    setSeasonRange("Spring");
  } else if (weather.temp >= 16 && weather.temp <= 50) {
    setSeasonRange("Sommer");
  } else if (weather.temp >= 6 && weather.temp <= 18) {
    setSeasonRange("Fall");
  } else if (weather.temp <= 7) {
    setSeasonRange("Winter");
  }

The state should set depending on weather.temp

Upvotes: 0

Views: 191

Answers (1)

ManZzup
ManZzup

Reputation: 526

You could use useEffect() with an empty array as the second argument to prevent it observing any states. So it would essentially only run once.

function DashboardHeaderContent({ looks, weather }) {
  const [seasonRange, setSeasonRange] = React.useState();

  function renderLook(look) {
    return <Look id={look._id} img={look.img} title={look.title} />;
  }
  
  useEffect(() => {
    if (weather.temp >= 7 && weather.temp <= 16) {
      setSeasonRange("Spring");
    } else if (weather.temp >= 16 && weather.temp <= 50) {
      setSeasonRange("Sommer");
    } else if (weather.temp >= 6 && weather.temp <= 18) {
      setSeasonRange("Fall");
    } else if (weather.temp <= 7) {
      setSeasonRange("Winter");
    }
  }, []);

 

Upvotes: 4

Related Questions