With React's class-based components, the component's state values can be read from within a setInterval within a class method, as logic elsewhere in the component changes the state:
...
constructor(props) {
super(props);
this.state = {
someChangingStateValue: 'initial value'
}
}
...
// Elsewhere, at random:
this.setState({someChangingStateValue: 'suddenly changed'})
...
_handleLoop() {
setInterval(() => {
console.log(this.state.someChangingStateValue)
console.log("The above line prints the current state value correctly.")
}, 500)
}
...
However, this pattern can't be used with hooks-based functional React components:
...
[someChangingStateValue, setSomeChangingStateValue] = useState('initial value')
...
// Elsewhere, at random:
setSomeChangingStateValue('suddenly changed')
...
const _handleLoop () => {
setInterval(() => {
console.log(someChangingStateValue)
console.log("The above line would always print 'initial value'.")
}, 500)
}
...
What is the best way to accomplish this with these functional components?