Carter Nabors
Carter Nabors

Reputation: 67

React not re-rendering style changes with useState

I am trying to update a animation speed with a button. When the button is pressed, nothing changes, but when the tab is switched, it updates to the speed that is set.

function Homepg() {

  const [speed, setSpeed] = useState(15);

  function faster () {
    setSpeed(speed === 1 ? speed : speed-2)
  };

  function slower() {
    setSpeed(speed+2);
  }

  const animationStyle = {
    animation: `App-logo-spin infinite ${speed}s linear`
  }

  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} style={animationStyle} className="App-logo-circle" alt="White cross, with a blue bacground spining" id='spinnerLogo'/>
        <p>Hello, and welcome to the begining of the Swiss Plus Website. <strong>We hope you enjoy your stay</strong></p>
        <button className='App-button' id='fastLogoButton' onClick={faster}>Increase Spin Speed!</button>
        <button className='App-button' id='slowLogoButton' onClick={slower}>Decrease Spin Speed!</button>
      </header>
    </div>
  );
}

Upvotes: 1

Views: 56

Answers (1)

Yuan-Hao Chiang
Yuan-Hao Chiang

Reputation: 2613

I just tested your code, and the speed itself does change (if you inspect the HTML node itself you will see the right time).

I believe the reason it doesn't work is because your CSS animation is set to infinite, so in theory, the animation is still running (alt-tabbing probably refreshes the animation as it is not running when the tab is hidden).

You could recreate the DOM node itself when the speed changes by setting a new key (forcing the img node to be recreated):

<img key={speed} src={logo} style={animationStyle} className="App-logo-circle" id='spinnerLogo'/>     

But that would reset the animation which would look jaggy and is not optimal.

I would suggest using react-spring which will allow you to fine-tune the animation.

Upvotes: 1

Related Questions