I have been profiling a React app using Chrome dev tools and I've discovered a linearly increasing Listener
count. Take a look at the screenshot below. The Listeners
are in orange.
I narrowed it down to a simple countdown value render inside p
tags. The remaining time is generated using setInterval function every 1000ms and then formatted and rendered inside the p
tags.
I created a simple React app using create-react-app
and modified the code inside the App.js's App component to update the value of Date.now() every second, and when I ran the profiler on it, I got the same result.
class App extends Component {
state = {
text: '',
};
loop() {
this.setState({ text: Date.now() });
}
componentWillMount() {
this.timer = setInterval(this.loop.bind(this), 1000);
}
componentWillUnmount() {
clearInterval(this.timer);
}
render() {
return (
<div className="App">
<p>{this.state.text}</p>
</div>
);
}
}
export default App;
What are these so called
Listeners
to begin with?Could the increasing Listener be indicative of a
memory leak
?If yes, how can you avoid this if you have to display a countdown or timer which updates the time/remaining time every second or faster?
BTW, do you also see that the JS Heap usage seems to be going up as well, despite all those garbage collections? That is weird, isn't it?
Cheers
setInterval
get called more than once? Because you never cancel that timer. – Gardia