class Clock extends React.Component {
constructor(props) {
super(props);
this.state = {date: new Date()};
}
componentDidMount() {
this.timerID = setInterval(
() => this.tick(),
1000
);
}
componentWillUnmount() {
clearInterval(this.timerID);
}
tick() {
this.setState({
date: new Date()
});
}
render() {
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {this.state.date.toLocaleTimeString()}.</h2>
</div>
);
}
}
ReactDOM.render(
<Clock />,
document.getElementById('root')
);
const Clock = (props) => {
const [date, setDate] = useState(new Date());
useEffect(() => {
const tick = () => {
setDate(new Date());
};
const timerID = setInterval(tick, 1000);
return () => clearInterval(timerID);
}, [])
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {date.toLocaleTimeString()}.</h2>
</div>
);
};
ReactDOM.render(
<Clock />,
document.getElementById('root')
);
'So when you're thinking: "Hey, my dependencies list needs to be []" don't do that because you think it only needs to run on mount, do it because you know that the stuff it's doing will never get stale.'
-- Kent Dodds