How to do it...

Build a LifeCycleTime component whose only purpose would be to display the current time. The component will be updated every 100 ms to keep the component in sync with the time change. We will use the life cycle methods in this component for the following purposes:

  • constructor(props): To initialize the component's initial state.
  • static getDerivedStateFromProps(nextProps, nextState): To merge the props with the state.
  • componentDidMount(): To set a function that will be executed every 100 ms using setInterval, which will update the state with the current time.
  • shouldComponentUpdate(nextProps, nextState):To decide if the component should be rendered or not. Check if props have a property dontUpdate set to true, which means the component shouldn't be updated on a state or props change.
  • componentDidUpdate(prevProps, prevState, snapshot): To simply log in the console that the component has been updated displaying the snapshot's value.
  • getSnapshotBeforeUpdate(prevProps, prevState): To illustrate the functionality of this method, simply return a string that will be passed as the third argument to componentDidUpdate.
  • componentWillUnmount(): When the component is destroyed or unmounted, clear the interval defined in componentDidMount. Otherwise, after the component is unmounted, you will see an error being displayed.

First, create an index.html file where you will render the React application:

  1. Create a new file named index.html
  2. Add the following code:
      <!DOCTYPE html> 
      <html lang="en"> 
      <head> 
          <meta charset="UTF-8"> 
          <title>Life cycle methods</title> 
      </head> 
      <body> 
          <div role="main"></div> 
          <script src="./stateful-react.js"></script> 
      </body> 
      </html> 
  1. Save the file

Next, perform the following steps to build the LifeCycleTime component:

  1. Create a new file named stateful-react.js
  2. Import the React and ReactDOM libraries:
      import * as React from 'react' 
      import * as ReactDOM from 'react-dom' 
  1. Define a LifeCycleTime class component and use the life cycle methods as previously described:
      class LifeCycleTime extends React.Component { 
          constructor(props) { 
              super(props) 
              this.state = { 
                  time: new Date().toTimeString(), 
                  color: null, 
                  dontUpdate: false, 
              } 
          } 
          static getDerivedStateFromProps(nextProps, prevState) { 
              return nextProps 
          } 
          componentDidMount() { 
              this.intervalId = setInterval(() => { 
                  this.setState({ 
                      time: new Date().toTimeString(), 
                  }) 
              }, 100) 
          } 
          componentWillUnmount() { 
              clearInterval(this.intervalId) 
          } 
          shouldComponentUpdate(nextProps, nextState) { 
              if (nextState.dontUpdate) { 
                  return false 
              } 
              return true 
          } 
          getSnapshotBeforeUpdate(prevProps, prevState) { 
              return 'snapshot before update' 
          } 
          componentDidUpdate(prevProps, prevState, snapshot) { 
              console.log( 
                  'Component did update and received snapshot:', 
                  snapshot, 
              ) 
          } 
          render() { 
              return ( 
                  <span style={{ color: this.state.color }}> 
                      {this.state.time} 
                  </span> 
              ) 
          } 
      } 
  1. Then, define an App class component, which will be used for testing your previously created component. Add three buttons: one that will toggle the color property between red and blue and pass it as a prop to the LifeCycleTime component, another button for toggling the dontUpdate property in the state between true and false, which will then be passed as a prop to the LifeCycleTime, and finally, a button that when clicked will either mount or unmount the LifeCycleTime component:
      class App extends React.Component { 
          constructor(props) { 
              super(props) 
              this.state = { 
                  color: 'red', 
                  dontUpdate: false, 
                  unmount: false, 
              } 
              this.toggleColor = this.toggleColor.bind(this) 
              this.toggleUpdate = this.toggleUpdate.bind(this) 
              this.toggleUnmount = this.toggleUnmount.bind(this) 
          } 
          toggleColor() { 
              this.setState((prevState) => ({ 
                  color: prevState.color === 'red' 
                      ? 'blue' 
                      : 'red', 
              })) 
          } 
          toggleUpdate() { 
              this.setState((prevState) => ({ 
                  dontUpdate: !prevState.dontUpdate, 
              })) 
          } 
          toggleUnmount() { 
              this.setState((prevState) => ({ 
                  unmount: !prevState.unmount, 
              })) 
          } 
          render() { 
              const { 
                  color, 
                  dontUpdate, 
                  unmount, 
              } = this.state 
              return ( 
                  <React.Fragment> 
                      {unmount === false && <LifeCycleTime 
                          color={color} 
                          dontUpdate={dontUpdate} 
                      />} 
                      <button onClick={this.toggleColor}> 
                          Toggle color 
                          {JSON.stringify({ color })} 
                      </button> 
                      <button onClick={this.toggleUpdate}> 
                          Should update? 
                          {JSON.stringify({ dontUpdate })} 
                      </button> 
                      <button onClick={this.toggleUnmount}> 
                          Should unmount? 
                          {JSON.stringify({ unmount })} 
                      </button> 
                  </React.Fragment> 
              ) 
          } 
      } 
  1. Render the application:
      ReactDOM.render( 
          <App />, 
          document.querySelector('[role="main"]'), 
      ) 
  1. Save the file.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.218.188.95