Advertisement
karlakmkj

React (JSX) - Lifecycle methods 3

Feb 9th, 2021
179
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import React from 'react';
  2.  
  3. export class Clock extends React.Component {
  4.   constructor(props) {
  5.     super(props);
  6.     this.state = { date: new Date() };
  7.   }
  8.   render() {
  9.     return <div>{this.state.date.toLocaleTimeString()}</div>;
  10.   }
  11.   componentDidMount() {
  12.     const oneSecond = 1000;
  13.     this.intervalID = setInterval(() => {  //Save the interval ID into a variable
  14.       this.setState({ date: new Date() });
  15.     }, oneSecond);
  16.   }
  17.   componentWillUnmount(){  //Add the new method that cleans up the interval
  18.     clearInterval(this.intervalID);
  19.   }
  20. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement