Listing 4-33: Fixing a memory leak
The current count is: 3.
import {Component} from 'react';
class NoLeakCounter extends Component{
constructor(){
super();
this.state = {count: 0};
this.incrementCount = this.incrementCount.bind(this);
}
incrementCount(){
this.setState({count: this.state.count + 1});
console.log(this.state.count);
}
componentDidMount(){
this.interval = setInterval(()=>{
this.incrementCount();
},1000)
}
componentWillUnmount(){
clearInterval(this.interval);
}
render(){
return (<p>The current count is: {this.state.count}.</p>);
}
}
export default NoLeakCounter;
import {useState} from 'react';
import NoLeakCounter from './NoLeakCounter';
function NoLeakCounterController() {
const [displayCounter,setDisplayCounter] = useState(true);
function toggleCounter(){
setDisplayCounter(!displayCounter);
};
return (
<div className="App">
{displayCounter ? <NoLeakCounter /> : null}
<button onClick={toggleCounter}>Toggle Count</button>
</div>
);
}
export default NoLeakCounterController;
Download the examples, report issues, and ask/answer questions in the discussion area by visiting the book's github page. All of the code for the book is also available on codesandbox.io for you to play around with.
ReactJS Foundations is published by John Wiley and Sons, Inc and is available in paperback and eBook.