How To Add Lifecycle Methods To a Class In ReactJS?


Every component in React has a lifecycle that incorporates several phases. Programmers usually think of this lifecycle as the component’s ‘lifetime’. The components experience the following events: Mounting, Updating, Unmounting, and Error handling. Mounting refers to the procedure of adding nodes and updating requires programmers to alter and change these nodes in the DOM. Unmounting, on the other hand, removes nodes and error handling tracks your code to ensure it works and is bug-free.

These occurrences can be compared to a component's birth, development, and eventual demise. You can override multiple lifecycle methods in each React lifecycle phase to execute code at particular points in the process. With this in mind, let's shed some light on how to add the above lifecycle methods to a Class component in ReactJS.

Detailed Insights On React Lifecycle Methods

As you know, mounting, updating, and unmounting are primary React Lifecycle methods. The methods used in each phase make it simpler to carry out common operations on the components. React developers can directly extend from React Component with class-based components to access the methods.

The most popular method for managing lifecycle events needed ES6 class-based components prior to React 16.8. In other words, if our code were already written using functional React components, we would need to rewrite those as classes that extend with React.Component and include a specific render function.

The three most popular lifecycle methods, componentDidMount, componentDidUpdate, and componentWillUnmount, could be accessed only then.

How To Use Local State And Extra Features With Ease?

In order to use local state along with extra features in React, you will first have to convert a functional complement to a class component.

  • Create a React.Component extending ES6 class of the same name
  • Add an empty method render().
  • Place the function's body in the render() method.
  • Substitute props in the render() body with this.props
  • Delete any remaining empty function declarations.
render() { return ( <div> <h1>Hello, world!</h1> <h2>It is {this.props.date.toLocaleTimeString()}.</h2> </div> ); }

The definition of the React component clock is now a class instead of a function. Every time an update occurs, the render method will be invoked, but as long as the <Clock/> element is rendered in the same DOM node, just one instance of the class would be used.

Adding Lifecycle Methods to a Class Component

For applications that incorporate a multitude of components, it’s imperative to free up resources. When the clock is first shown to the DOM, we want to start a timer. The React term for this is "mounting." Additionally, once the DOM created by the clock is deleted, we want to reset that timer. In React, this is referred to as "unmounting."

Example

import react from ‘react’; 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> ); } }

Output

Hello, world!
It is 10:27:03 AM.

Successfully rendering the component’s output invokes a particular function. This is the componentDidMount() function. Insert a timer here −

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

It is further possible to insert more fields manually to the Class component. Programmers usually do this when they need to keep something which wasn’t a part of the data flow. Reg despite ReactJS setting up this.state and this.props by itself. These further possess unique meanings like a timer ID. In the lifecycle function componentWillUnmount(), we shall deactivate the timer −

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

The Clock component will execute the tick() method, which we will implement last, once every second. It will employ this. To program updates to the component's local state, use setState() −

Example

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/>);

Output

Hello, world!
It is 10:30:12 AM. //clock is ticking every second.
The clock is now ticking every second.

Using State Correctly

You should be aware of three aspects concerning setState().

Do Not Modify State Directly

This won't re-render a component, for example −

// Wrong this.state.comment = 'Hello'; Instead, use setState(): // Correct this.setState({comment: 'Hello'});

Only the constructor is capable of assigning this.state.

State Updates May Be Asynchronous

You shouldn't use this.props, and this.state's values to determine the next state because they might be modified asynchronously. For example, the following code won’t be applicable while updating the counter −

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

Instead, refer to other versions of setState() and utilize the one which accepts functions. This is because a few versions see functions as an object that requires fixing. The previous state will be passed as the first argument to that method, and the props present at the moment the update is applied will be passed as the second argument −

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

Although we used an arrow function in the example above, normal functions also work −

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

State Updates are Merged

Your state might include a number of independent variables −

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

After that, you may update each one separately using different setState() calls −

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

this.setState(comments) totally replaces this.state.comments but does just a superficial merging, leaving this.state.posts unaltered.

Thus, the state component is often considered local or contained. Other than the component that owns and controls it, no other component has access to it.

Bottom Line

We have discussed everything you need to know to add lifecycle methods correctly to Class Components in React. Many programmers generally encounter several difficulties while doing the same because of the codes and technicality involved. Therefore, make sure to follow the steps correctly and cross-check your codes before running a command.

Updated on: 23-Aug-2022

170 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements