ReactJS | Understanding State and Lifecycle

ReactJS Understanding State and Lifecycle

Hello React Developers,

In this guide, we will learn about the State and Lifecycle of ReactJS. 

ReactJS is the most widely used Javascript library for websites and mobile applications. This article will familiarize us with the essential concepts of ReactJS – state and lifecycle.

What is State in React?

The state in React holds some information that keeps changing during the components’ lifetime. The state is a built-in ReactJS object. The state of a component changes with time and whenever it changes, the component re-renders. this.setState() is used to change the value of the state object. setState() function merges the new and the previous state.

How to Use State correctly in React?

There are three things you should know about setState()

Do Not Modify State Directly

Instead of using the below function,

this.state.comment = ‘Hello';

Use setState() as below

this.setState({comment: 'Hello'});

State Updates May Be Asynchronous

React may batch multiple setState() calls into a single update for performance. Because this.props and this.state may be updated asynchronously, you should not rely on their values for calculating the next state.

For example, the below code may fail to update the counter:

this.setState({
    counter: this.state.counter + this.props.increment,
});

To fix it, use the second form of setState() that accepts a function rather than an object. That function will receive the previous state as the first argument and the props at the time the update is applied as the second argument:

this.setState((state, props) => ({
    counter: state.counter + props.increment
}));

We used an arrow function above, but it also works with regular functions:

this.setState(function(state, props) {
    return {
        counter: state.counter + props.increment
    };
});

State Updates are Merged

When you call setState(), React merges the object you provide into the current state.

For example,

constructor(props) {
    super(props);
    this.state = {
        posts: [],
        comments: []
    };
}

After that, you can update them individually with setState()

componentDidMount() {
    fetchPosts().then(response => {
        this.setState({
            posts: response.posts
        });
    });
    fetchComments().then(response => {
        this.setState({
            comments: response.comments
        });
    });
}

The merging is shallow, so this.setState({comments}) leaves this.state.posts intact, but completely replaces this.state.comments.

Lifecycle in React

Each React component has a lifecycle. In regular terms, a lifecycle means birth, growth, and death. In the same way, the React components are also initiated unknown as mounting, then they are updated, which means its growth, and they die, known as demounting. This is the lifecycle of components in React.

Example of React State and Lifecycle

Consider the ticking clock example. In Rendering Elements, we have only learned one way to update the UI. We call root.render() to change the rendered output:

const root = ReactDOM.createRoot(document.getElementById('root'));
function tick() {
    const element = (
       <div>
            <h1>Hello, world!</h1>
            <h2>It is {new Date().toLocaleTimeString()}.</h2>
        </div>
    );
    root.render(element);
}
setInterval(tick, 1000);

We will learn how to make the Clock component truly reusable and encapsulated. It will set up its own timer and update itself every second.

We can start by encapsulating how the clock looks:

const root = ReactDOM.createRoot(document.getElementById('root'));
function Clock(props) {
    return (
        <div>
            <h1>Hello, world!</h1>
            <h2>It is {props.date.toLocaleTimeString()}.</h2>
        </div>
    );
}

function tick() {
    root.render(<Clock date={new Date()} />);
}
setInterval(tick, 1000);

However, it misses a crucial requirement: the fact that the Clock sets up a timer and updates the UI every second should be an implementation detail of the Clock. Ideally, we want to write this once and have the Clock update itself:

root.render(<Clock />);

Adding Lifecycle Methods to a Class 

In applications with many components, it’s vital to free up resources taken by the 

components when they are destroyed. We want to set up a timer whenever the Clock is rendered to the DOM for the first time. This is called “mounting” in React. We also want to clear that timer whenever the DOM produced by the Clock is removed. This is called “unmounting” in React. We can declare special methods on the component class to run some code when a component mounts and unmounts:

class Clock extends React.Component {
    constructor(props) {
        super(props);
        this.state = {date: new Date()};
    }
    componentDidMount() {
    }
    componentWillUnmount() {
    }
    render() {
        return (
            <div>
                <h1>Hello, world!</h1>
                <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
            </div>
        );
    }
}

These methods are called “lifecycle methods”.

The componentDidMount() method runs after the component output has been rendered to the DOM. This is a good place to set up a timer:

componentDidMount() {
    this.timerID = setInterval(
        () => this.tick(),
        1000
    );
}

We will tear down the timer in the componentWillUnmount lifecycle method:

componentWillUnmount() {
    clearInterval(this.timerID);
}

Finally, we will implement a method called tick() that the Clock component will run every second. It will use this.setState() to schedule updates to the component local state:

class Clock extends React.Component {
    constructor(props) {
        super(props);
        this.state = {date: new Date()};
    }
    componentDidMount() {
        this.timerID = setInterval(
            () => this.tick(),
            1000
        );
    }
    componentWillUnmount() {
        clearInterval(this.timerID);
    }
    tick() {
        this.setState({
            date: new Date()
        });
    }
    render() {
        return (
            <div>
                <h1>Hello, world!</h1>
                <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
            </div>
        );
    }
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Clock />);

Conclusion:

That’s it! We covered the most important concepts in React, State and Lifecycle. If you have any doubts, feel free to ask me through the comment section. If you found the article helpful, hit five stars and stay updated to learn more about ReactJS.

Previous Article

How to Use Schema.org Markup for Your E-Commerce Sites

Next Article

Magento 2 Admin Actions Log Extensions of 2024 [UPDATED]

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *

Get Connect With Us

Subscribe to our email newsletter to get the latest posts delivered right to your email.
Pure inspiration, zero spam ✨