1

I have a very simple react code that doesn't work.

The value of the rotation from the console.log inside setTimeout is always { speed: 0, spinning: false } which was its initial value.

When do you actually use useState? What hook should I use for this simple code to work?

import React, { useEffect, useState } from 'react';
import './style.css';

export default function App() {
  const [rotation, setRotation] = useState({ speed: 0, spinning: false });

  const handleRotation = () => {
    if (!rotation.spinning) {
      setRotation({ speed: 0.02, spinning: true });
      setTimeout(() => {
        console.log(rotation);
        setRotation({ speed: 0, spinning: false });
      }, 3000);
    }
  };

  return (
    <div>
      <button onClick={handleRotation}>Spin</button>
    </div>
  );
}

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
lueenavarro
  • 528
  • 10
  • 20
  • Here is a stackblitz: https://stackblitz.com/edit/react-ehzhua – lueenavarro Jan 14 '22 at 12:16
  • Anything which isn't a state will be re-calculated on each render. States will persist between renders. – Emil Karlsson Jan 14 '22 at 12:17
  • 2
    Your `setTimeout` handler closes over the old copy of `rotation`. If you want the new one, you have to use the callback version of `setRotation`, so you're looking at the current copy of it. See the [linked question's answers](https://stackoverflow.com/questions/62247056/usestate-updated-state-not-available-in-the-same-handler-even-with-timeout) for details. – T.J. Crowder Jan 14 '22 at 12:18

0 Answers0