Advertisement
karlakmkj

React (JSX) - Lifecycle methods

Feb 8th, 2021
194
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import React from 'react';
  2. import ReactDOM from 'react-dom';
  3.  
  4. class Clock extends React.Component {
  5.   // Add your methods in here.
  6.   constructor(props){    // the constructor is the first thing called when the component instance is mounted.
  7.     super(props);
  8.     this.state = {date: new Date()}
  9.   }
  10.   render(){    //render() will be called when <Clock /> mounts and whenever it updates, as part of its lifecycle.
  11.     return <div>
  12.      {this.state.date.toLocaleTimeString()}  //This will "wire up” the state to the screen. Notice that this is static—it doesn’t update, even as time goes by.
  13.     </div>
  14.   }
  15. }
  16. /*
  17. The constructor is the first thing called during mounting. render() is called later, to show the component for the first time. If it happened in a different order, render() wouldn’t have access to this.state, and it wouldn’t work.
  18.  
  19. Notice that lifecycle methods don’t necessarily correspond one-to-one with part of the lifecycle. constructor() only executes during the mounting phase, but render() executes during both the mounting and updating phase.
  20. */
  21. ReactDOM.render(<Clock />, document.getElementById('app'));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement