Loading {count} %

); The cou" />

Loading {count} %

); The cou" />

Loading {count} %

); The cou"/>

Change color of a div depending on state value using useEffect? React

37 views Asked by At

I have a div that that has a counter inside of it.

return (
    <div 
      className="loading-div"
      style={styles}
    >
      <h1>Loading {count} %</h1>
    </div>
  );

The counter is updated using a setTimeout function that updates it's value every .1 seconds. This setTimeout function is set inside of a useEffect hook.

useEffect((e) => {
    setTimeout(() => {
      count === 100 ? e.preventDefault() : setCount(() => count + 1);
      count === 35 ? setFont(() => font + 6) : setCount(() => count + 1);
      count === 70 ? setWidth(() => width + 100) : setCount(() => count + 1);
      count === 70 ? setHeight(() => height + 100) : setCount(() => count + 1);
      count === 99 ? setColor(() => color="lime") : setCount(() => count + 1);
    }, 100);
  })

Everything seems to work properly until the counter gets to 99, then the div disappears.

I assume that the fontSize and width/height work because I use font + 5 but the setColor function does not work because I assign the color but the state doesn't immediately change? How can I make it so that the state changes immediately as soon as my counter reaches 99?

1

There are 1 answers

0
atanasovlj On

To answer my own question, I found that placing setColor inside of another function and then calling that function fixes my problem.

const getColor = () => setColor();

count === 99 ? getColor(() => setColor(() => color="lime")) : setCount(() => count + 1);