We now have a youtube channel. Subscribe!

ReactJS | Component Life Cycle using React Hooks

ReactJS | Component Life Cycle using React Hooks


Hello folks! welcome back to a new section of our tutorial on ReactJS. In this section of our tutorial on ReactJS, we will be studying about ReactJS Component Life Cycle using React Hooks.

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

The syntax of useEffect() api is as follows -

useEffect(
   <executeFn>, 
   <values>
);

Here,

  • executeFn - Function to execute when an effect takes place with an optional return function. The return function is executed when a cleanup is required.
  • values - This is an array of values that the effect depends upon. React Hooks executes the executeFn only when the values are changed. This will decrease unnecessary calling of the executeFn.

Let's include 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 time and date 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 used to set the current time into the state of the React component.
  • Called the setInterval JavaScript api to execute setTime every second and we stored the reference of the setInterval in the interval variable.
  • Created a return function, which calls the clearInterval api to stop executing the setTime every second by passing the interval reference.


Now, we have updated the clock component and the complete 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 file and use setTimeout to remove the clock from the DOM after five 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 making use of npm command.

npm start

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

The clock will be displayed for five seconds and then, it is going to be removed from the DOM. By checking the console log, we can find that the cleanup code is well executed.


React Children Property

React allows random children user interface content to be added in the component. The children of the component can be accessed through this.props.children. Adding children inside the component is called containment. Containment is used in circumstance where some 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 make RichTextMessage component to show the feature of React children property in this tutorial.

First, create a new react application, react-message-app via Create React App or Rollup bundler by following the instruction given in Creating a React application tutorial.

READ: ReactJS | State Management using React Hooks

Next, open the application via your favorite editor.

Next, create an src folder beneath the root directory of the application.

Next, create component folder beneath src folder.

Create a file, RichTextMessage.js under the src/component 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, include render() method and show the user interface of the component along with its children.

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

Here,

  • props.children returns the children of the component.
  • We wrapped the children inside a div tag.

Finally, export the component.

export default RichTextMessage;

The complete code of the RichTextMessage component 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 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 making use of npm command.

npm start

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


The browser displays component's children wrapped in a div tag as shown below -

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

Next, you have to 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, the browser updates the component's children content and displays the results as shown below -

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


Alright guys! This is where we are going to be rounding up for this tutorial. In our next tutorial, we will be discussing about Layout in Component.

Feel free to ask your questions where necessary and we will attend to them as soon as possible. If this tutorial was helpful to you, you can use the share button to share this tutorial.

Follow us on our various social media platforms to stay updated with our latest tutorials. You can also subscribe to our newsletter in order to get our tutorials delivered directly to your emails.

Thanks for reading and bye for now.

Post a Comment

Hello dear readers! Please kindly try your best to make sure your comments comply with our comment policy guidelines. You can visit our comment policy page to view these guidelines which are clearly stated. Thank you.
© 2022 ‧ WebDesignTutorialz. All rights reserved. Developed by Jago Desain