Skip to content

Contact sales

By filling out this form and clicking submit, you acknowledge our privacy policy.

Execute JavaScript after the React.js Render Method Completes

May 28, 2020 • 9 Minute Read

Introduction

React isn't an MVC (Model View Controller) framework, but its architecture allows developers to write clean code by easily differentiating between the template, JavaScript, and styles. The render method contains the JSX template of the app comprised of all DOM elements. In order to execute JavaScript in your app, dedicated methods called lifecycle methods are used. This guide sheds more light on these methods and their use cases, allowing you to understand where to write your JavaScript after the DOM has rendered.

A React Component's Lifecycle

Every component in React goes through three phases: the mounting phase, the updating phase, and the unmounting phase. In the mounting phase, the component is created for the first time and mounted on the DOM, and the initial value of the state is set. This is followed by an updating phase where all the interactive functionalities of your app are catered to by comparing old props with new ones, updating the state, etc. Finally, the component is unmounted from the DOM and destroyed.

Component Lifecycle Methods

Throughout these phases, there are certain methods that you can tap into, called lifecycle methods. The render() takes care of the DOM elements and is invoked every time the component is mounted or updated. Thus ,any JavaScript that needs to be executed after the render method has completed can go inside two methods: ComponentDidMount() in the mounting phase and ComponentDidUpdate() in the updating phase. There are other relevant methods pertaining to these phases, but this guide will focus on these two due to their relevance to this topic.

Use Cases

The ComponentDidMount() method is usually used for initializing any third party components or plugins in your app. For instance, when you're using native CSS libraries like MaterializeCSS or Bootstrap for modals and popups, their JavaScript can be initialized inside this method. Additionally, if your component needs any initial data to display, all API calls to the server or an external database can be made here.

The ComponentDidUpdate() method is invoked after the component is updated through a well defined condition. In the absence of this condition, it will keep on invoking itself, causing an infinite loop and eventually breaking the app. Use this method if the state has changed after the first render method, and make sure it is not invoked before the first render call. If you have a profile page in your app that you want to render editable, this component can be used for updating the state and sending the updated data to the server.

Implementation and Example

Let's work through an example.

Setup

Make sure you have Nodejs and npm installed in your machine (at least version 8 or higher) along with a code editor and a web browser.

Create a new project using create-react-app:

      npx create-react-app react-javascript
    

Also install axios to make API calls by running this command:

      npm i axios
    

Clean up the Template

Remove the logo, App.css, and all their imports from App.js. Clean out the starter template inside the App component. Your App.js should look like the code below.

      import React,{Component} from 'react';
import axios from 'axios';

export default class App extends Component {
  constructor(){
    super();
   }
  
  render(){
   
    return (
      <div className="App">
             <h1>Welcome to App</h1>   
      </div>
    );
  }
}
    

Using componentDidMount()

Invoke componentDidMount() and call another local function inside it to handle the API call.

      ...
componentDidMount(){
    this.getUser();
  }
...
    

Inside the constructor, set up the state with an empty users object, which will be populated from the API's data.

      constructor(){
    super();
    this.state={
      users:[]
    }
  }
    

Create the async getUser() function and make an API call to get some external data. This guide uses a free demo REST API but you can also use your own here.

      async getUser(){
    let usersData=await axios.get('https://reqres.in/api/users?page=2')
                    .then(res=>{
                      return res.data.data;
                    })
                    .catch(err=>{
                      console.log(err);
                    })
    this.setState({
      users:usersData
    },()=>{console.log(this.state)})
  }
    

Finally, output this data on the DOM by cycling through the users array.

      render(){
    const {users}=this.state;
    return (
      <div className="App">
        {users && users.map(user=>{
          return(
            <div className="card" key={user.id}>
              <img src={user.avatar} alt="Avatar" style={{width:'auto'}}/>
              <div className="container" >
                <h4 ><b>{user.first_name}</b></h4>
                <p>{user.email}</p>
              </div>
            </div>
          )
        })}
        
      </div>
    );
  }
    

Your App.js should look like this:

      import React,{Component} from 'react';
import axios from 'axios';

export default class App extends Component {
  constructor(){
    super();
    this.getUser=this.getUser.bind(this);
    this.state={
      users:[]
    }
  }
  componentDidMount(){
    this.getUser();
  }
  async getUser(){
    let usersData=await axios.get('https://reqres.in/api/users?page=2')
                    .then(res=>{
                      return res.data.data;
                    })
                    .catch(err=>{
                      console.log(err);
                    })
    this.setState({
      users:usersData
    },()=>{console.log(this.state)})
  }
  render(){
    const {users}=this.state;
    return (
      <div className="App">
        {users && users.map(user=>{
          return(
            <div className="card" key={user.id}>
              <img src={user.avatar} alt="Avatar" style={{width:'auto'}}/>
              <div className="container" >
                <h4 ><b>{user.first_name}</b></h4>
                <p>{user.email}</p>
              </div>
            </div>
          )
        })}
        
      </div>
    );
  }
}
    

Using componentDidUpdate()

Sometimes when the stateful data changes its value and some subsequent API calls are made after the first render has invoked, componentDidUpdate() is used.

      componentDidUpdate(prevProps,prevState){
    if(this.props.id !== prevProps.id){
      //make an API call here and update the state
    }
  }
    

For example, if you want to update a list of users with a new set of users by comparing them, you can put a relevant condition inside this method and update the previous data with the new one.

Testing

Inside the root directory, run:

      npm start
    

This will spin up a local development server (usually on port 3000) and you can see the dummy data on the page. Feel free to style this the way you want.

Hooks Equivalent

After React v. 16.8.0, a stable version of React Hooks was introduced inside the core API that has made developing components much easier and faster. Hooks allow us to code the same component that was earlier based on an object-oriented model as a purely functional model. The render method is replaced by a simple return statement, and a common useEffect hook is manipulated to achieve different lifecycle methods. The hooks equivalent of componentDidMount() is as follows:

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

export default function App () {
  const[users,setUsers]=useState([]);

  useEffect(async()=>{
    let usersData=await axios.get('https://reqres.in/api/users?page=2')
                    .then(res=>{
                      return res.data.data;
                    })
                    .catch(err=>{
                      console.log(err);
                    })
    setUsers(usersData)
  },[])
  
    return (
      <div className="App">
        {users && users.map(user=>{
          return(
            <div className="card" key={user.id}>
              <img src={user.avatar} alt="Avatar" style={{width:'auto'}}/>
              <div className="container" >
                <h4 ><b>{user.first_name}</b></h4>
                <p>{user.email}</p>
              </div>
            </div>
          )
        })}
        
      </div>
    );
}
    

Conclusion

Component lifecycle methods give you a great way of handling certain core functionalities in your app. Understanding the lifecycle phases of a component is imperative to use them correctly. In this guide, you learned the most important use cases of the two most common lifecycle methods, along with their implementation in code, so as to understand how JavaScript can be written and executed after a component is added into the DOM tree.

Gaurav Singhal

Gaurav S.

Guarav is a Data Scientist with a strong background in computer science and mathematics. He has extensive research experience in data structures, statistical data analysis, and mathematical modeling. With a solid background in Web development he works with Python, JAVA, Django, HTML, Struts, Hibernate, Vaadin, Web Scrapping, Angular, and React. His data science skills include Python, Matplotlib, Tensorflows, Pandas, Numpy, Keras, CNN, ANN, NLP, Recommenders, Predictive analysis. He has built systems that have used both basic machine learning algorithms and complex deep neural network. He has worked in many data science projects, some of them are product recommendation, user sentiments, twitter bots, information retrieval, predictive analysis, data mining, image segmentation, SVMs, RandomForest etc.

More about this author