How to use React state variables in setInterval in a handler function

I have code that looks like the code below (I cut most out to highlight the problem). I'm trying to, on a button click, call a function that calls setInterval to increment the parent component's state. What's being logged is just "0", though. The "setPercent" dispatch function seems to be working fine - after it's called I know that "percent" is being updated to 1, but when it gets back around on the next interval the console logs 0 again and the set sets to 1 again. I'm assuming that what's happening is that when the "clickHandler" function is created it's hard copying the value of "percent" rather than referencing it - I don't know why though and how to fix it. Any help is greatly appreciated!

const Component = () => {
    const [percent, setPercent] = useState(0)

    const clickHandler = (time) => {
        let timer = setInterval(() => {
            if (percent < 100) {
                console.log('current percent', percent)
                setPercent(percent + 1)
            } else {
                clearInterval(timer)
            }
        }, time / 100)
    }

    return (
        <div>
            <Button onClick={clickHandler} />
        </div>
    )
}


Read more here: https://stackoverflow.com/questions/68474082/how-to-use-react-state-variables-in-setinterval-in-a-handler-function

Content Attribution

This content was originally published by Prolly Confused at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: