Friday, December 27, 2024
Google search engine
HomeLanguagesReactJS Lifecycle of Components

ReactJS Lifecycle of Components

In this article, we will learn how we can implement states in React and implement the lifecycle methods in React. These lifecycle methods are used to control the components at different stages from initialization till unmounting.

Phases in lifecycle of Components

  • Mounting(Component is added to the DOM)
  • Updating(Component is updated in the DOM)
  • Unmounting(Component is removed from the DOM)

reactjs-lifecycle-components-copy-2

Some of the basic lifecycle methods in React include render(), constructor, componentDidMount(), shouldComponentUpdate() etc.

Note: Since the version 16.3 of React some lifecycle methods like componentWillMount, componentWillReceiveProps, componentDidUpdate have been deprecated and are no longer in use. To use them we have to write UNSAFE_ before calling the method.

Let us see an example where we will implement state and lifecycle methods in React.

Open your react project directory and edit the Index.js file from the src folder.

First, we will create a timer without implementing state and lifecycle methods then we will see another example where we will update the state

Javascript




import React from 'react';
import ReactDOM from 'react-dom';
  
function showTime() {
    const myElement = (
        <div>
            <h1>Welcome to neveropen!</h1>
            <h2>{new Date().toLocaleTimeString()}</h2>
        </div>
    );
  
    ReactDOM.render(
        myElement,
        document.getElementById("root")
    );
}
  
setInterval(showTime, 1000)


Now what is the component in the above example? Actually, if you pay attention there is no component whatsoever. We are assigning a nested JSX element named “myElement” to contain the latest time and render the same every second, which is one of the worst ways to implement using React.

Creating clock by implementing state and lifecycle

Approach:

We define the class to be “Clock” we must think of the process first. Our clock has exactly two parts one is the title this should be implemented using props as it will not be changing throughout the lifetime; the other part is the time itself that should be changed at each second. It is clear that we have to set an interval to update the state at each second and this should be done as soon as the clock component is mounted. Thus, we have to use a lifecycle function componentDidMount() where we will set an interval to update the state, and to make the app efficient we will use componentWillUnmount() method to clear the interval. Let us see the following implementation. 

Open your react project directory and edit the Index.js file from src folder:

Example:

javascript




import React from 'react';
import ReactDOM from 'react-dom/client';
  
class Clock extends React.Component {
    constructor(props) {
        super(props);
        this.state = { time: new Date() };
    }
    // As soon as the Clock is mounted.
    // Start the interval "timer".
    // Call tick() every second.
    componentDidMount() {
        this.timer = setInterval(
            () => this.tick(),
            1000);
    }
    // Before unmounting the Clock,
    // Clear the interval "Timer"
    // This step is a memory efficient step.
    componentWillUnmount() {
        clearInterval(this.timer);
    }
    // This function updates the state,
    // invokes re-render at each second.
    tick() {
        this.setState({
            time: new Date()
        });
    }
  
    render() {
        return (
            <div>
                <h1>Welcome to {this.props.title} !</h1>
                <h2>{this.state.time.toLocaleTimeString()}</h2>
            </div>
        );
    }
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <Clock title="neveropen" />
  </React.StrictMode>
);


Output:

implementing state and lifecycle

Congratulations! You just created a React web app using States, Props, and some lifecycle methods. You might be asking is that all? No, it isn’t even a nibble of the whole platter stay tuned for the upcoming articles where we dive deeper into React and create some more projects on the go.

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments