ReactJS - Component Life Cycle Using React Hooks



React Hooks provides a special Hook, useEffect() to execute certain functionality during the life cycle of the component. useEffect() combines componentDidMount, componentDidUpdate, and componentWillUnmount life cycle into a single api.

The signature of the useEffect() api is as follows −

useEffect(
   <executeFn>, 
   <values>
);

Here,

  • executeFn − Function to execute when an effect occurs with an optional return function. The return function will be execute when a clean up is required (similar to componentWillUnmount).

  • values − array of values the effect depends on. React Hooks execute the executeFn only when the values are changed. This will reduce unnecessary calling of the executeFn.

Let us add useEffect() Hooks in our react-clock-hook-app application.

Open react-clock-hook-app in your favorite editor.

Next, open src/components/Clock.js file and start editing.

Next, import useEffect api.

import React, { useState, useEffect } from 'react';

Next, call useEffect with function to set date and time every second using setInterval and return a function to stop updating the date and time using clearInterval.

useEffect(
   () => {
      let setTime = () => {
         console.log("setTime is called");
         setCurrentDateTime(new Date());
      }
      let interval = setInterval(setTime, 1000);
      return () => {
         clearInterval(interval);
      }
   },
   []
);

Here,

  • Created a function, setTime to set the current time into the state of the component.

  • Called the setInterval JavaScript api to execute setTime every second and stored the reference of the setInterval in the interval variable.

  • Created a return function, which calls the clearInterval api to stop executing setTime every second by passing the interval reference.

Now, we have updated the Clock component and the complete source code of the component is as follows −

import React, { useState, useEffect } from 'react';

function Clock() {
   const [currentDateTime, setCurrentDateTime] = useState(new Date());
   useEffect(
      () => {
         let setTime = () => {
            console.log("setTime is called");
            setCurrentDateTime(new Date());
         }
         let interval = setInterval(setTime, 1000);
         return () => {
            clearInterval(interval);
         }
      },
      []
   );
   return (
      <div>
         <p>The current time is {currentDateTime.toString()}</p>
      </div>
   );
}
export default Clock;

Next, open index.js and use setTimeout to remove the clock from the DOM after 5 seconds.

import React from 'react';
import ReactDOM from 'react-dom';
import Clock from './components/Clock';

ReactDOM.render(
   <React.StrictMode>
      <Clock />
   </React.StrictMode>,
   document.getElementById('root')
);
setTimeout(() => {
   ReactDOM.render(
      <React.StrictMode>
         <div><p>Clock is removed from the DOM.</p></div>
      </React.StrictMode>,
      document.getElementById('root')
   );
}, 5000);

Next, serve the application using npm command.

npm start

Next, open the browser and enter http://localhost:3000 in the address bar and press enter.

The clock will be shown for 5 seconds and then, it will be removed from the DOM. By checking the console log, we can found that the cleanup code is properly executed.

Cleanup Code

React children property aka Containment

React allows arbitrary children user interface content to be included inside the component. The children of a component can be accessed through this.props.children. Adding children inside the component is called containment. Containment is used in situation where certain section of the component is dynamic in nature.

For example, a rich text message box may not know its content until it is called. Let us create RichTextMessage component to showcase the feature of React children property in this chapter.

First, create a new react application, react-message-app using Create React App or Rollup bundler by following instruction in Creating a React application chapter.

Next, open the application in your favorite editor.

Next, create src folder under the root directory of the application.

Next, create components folder under src folder.

Next, create a file, RichTextMessage.js under src/components folder and start editing.

Next, import React library.

import React from 'react';

Next, create a class, RichTextMessage and call constructor with props.

class RichTextMessage extends React.Component {
   constructor(props) { 
      super(props); 
   } 
}

Next, add render() method and show the user interface of the component along with it's children

render() { 
   return ( 
      <div>{this.props.children}</div> 
   ) 
}

Here,

  • props.children returns the children of the component.

  • Wraped the children inside a div tag.

Finally, export the component.

export default RichTextMessage;

The complete source code of the RichTextMessagecomponent is given below −

import React from 'react';

class RichTextMessage extends React.Component {
   constructor(props) {
      super(props);
   }
   render() {
      return (
         <div>{this.props.children}</div>
      )
   }
}
export default RichTextMessage;

Next, create a file, index.js under the src folder and use RichTextMessage component.

import React from 'react';
import ReactDOM from 'react-dom';
import RichTextMessage from './components/RichTextMessage';

ReactDOM.render(
   <React.StrictMode>
      <RichTextMessage>
         <h1>Containment is really a cool feature.</h1>
      </RichTextMessage>
   </React.StrictMode>,
   document.getElementById('root')
);

Finally, create a public folder under the root folder and create index.html file.

<!DOCTYPE html>
<html lang="en">
   <head>
      <meta charset="utf-8">
      <title>React App</title>
   </head>
   <body>
      <div id="root"></div>
      <script type="text/JavaScript" src="./index.js"></script>
   </body>
</html>

Next, serve the application using npm command.

npm start

Next, open the browser and enter http://localhost:3000 in the address bar and press enter.

Cleanup Codes

Browser emits component's children wrapped in div tag as shown below −

<div id="root">
   <div>
      <div>
         <h1>Containment is really a cool feature.</h1>
      </div>
   </div>
</div>

Next, change the child property of RichTextMessage component in index.js.

import React from 'react';
import ReactDOM from 'react-dom';
import Clock from './components/Clock';

ReactDOM.render(
  <React.StrictMode>
         <RichTextMessage>
            <h1>Containment is really an excellent feature.</h1>
         </RichTextMessage>
   </React.StrictMode>,
   document.getElementById('root')
);

Now, browser updates the component's children content and emits as shown below −

<div id="root">
    <div>
        <div>
            <h1>Containment is really an excellent feature.</h1>
        </div>
    </div>
</div>

In short, containment is an excellent feature to pass arbitrary user interface content to the component.

Advertisements