Why callback inside react function component is using outdated state?

Viewed 20

I've created a simple react component where I want to run a function every 5s. Unfortunately, function that I'm passing to setInterval is using outdated state (I mean it keeps logging Fun IntervalID: null while component is displaying proper intervalID). Also in react devtools it can be seen that intervalID has been updated. What could be the reason for such behaviour? How come I can update IntervalID from fun using setIntervalID what is then presented on the UI, but cannot access current intervalID value?

Here is a code snippet:

import React, {useEffect, useState} from "react";

const Component1 = () => {
    const [intervalID, setIntervalID] = useState(null);
    const [response, setResponse] = useState(null);

    const fun = async () => {
        console.log("Fun IntervalID: " + new String(intervalID));
        setIntervalID(Math.floor(Math.random() * 100));
    };

    const runFun = () => {
        const newIntervalID = setInterval(fun, 5000);
        setIntervalID(newIntervalID);
    };

    useEffect( () => {
        runFun();
    }, [response]);

    return (
        <>
            {intervalID}
        </>
    );
};

export default Component1;

Thank you for all your help.

0 Answers
Related