I'm trying to periodically run a calculation (every 5 seconds) and update a component's state with the calculated value using a setInterval
timer. What I've seen is that the updateCalculation()
function does get called every 5 seconds but when monitoring the memory usage using the Chrome devtools it just keeps on growing endlessly on every call by setInterval
. The memory never seems to get released.
Snapshot 1:
Snapshot 2:
What could be a possible workaround for running calculations periodically? I'm still pretty new to React and am really not sure what I'm doing wrong.
class MyComponent extends React.PureComponent {
constructor(props) {
super(props);
this.state = {
calculated: []
};
}
componentDidMount() {
this.calculationUpdater = setInterval(() => this.updateCalculation(), 5000);
}
componentWillUnmount() {
clearInterval(this.calculationUpdater);
}
// Memory leak here
// The function that gets called by setInterval to calculate data and update the state
updateCalculation() {
let data = [];
for (let i = 0; i < 60000; i++) {
data.push({x: i, y: i, z: i});
}
this.setState({
calculated: data
});
}
render() {
return (
<React.Fragment>
<Child calc={this.state.calculated} />
</React.Fragment>
);
}
}
I'm not doing anything special with the Child
component at the moment. This is what it looks like:
class Child extends React.PureComponent {
render() {
return (
<div></div>
);
}
}