Lukas
Lukas

Reputation: 149

How to get updated useState() value inside timeout function?

I'm currently trying to get the latest updates into a timeout function. This means I want to have c updated to 1 without having to use something like the useRef hook.

const [c, s] = useState<number>(0)

    const f = () => {
        s(1)
        setTimeout(() => console.log(c), 600)
    }

    return (
        <div
            style={{ width: '100%', height: '100%', backgroundColor: 'black' }}
            onMouseEnter={f}
        >
            test
        </div>
    )

Upvotes: 0

Views: 140

Answers (1)

Dennis Vash
Dennis Vash

Reputation: 53884

Without a reference, you can try useEffect hook:

const [c, setC] = useState<number>(0);

useEffect(() => {
  setTimeout(() => {
    console.log(c);
  }, 600);
}, [c]);

const f = () => {
  setC(1);
};

return <div onMouseEnter={f}>test</div>;

Upvotes: 2

Related Questions