Important Update
The Guide Feature will be discontinued after December 15th, 2023. Until then, you can continue to access and refer to the existing guides.
Author avatar

Gaurav Singhal

Execute JavaScript after the React.js Render Method Completes

Gaurav Singhal

  • May 28, 2020
  • 9 Min read
  • May 28, 2020
  • 9 Min read
Web Development
Front End Web Development
Client-side Framework


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.


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:

1npx create-react-app react-javascript

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

1npm 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.

1import React,{Component} from 'react';
2import axios from 'axios';
4export default class App extends Component {
5  constructor(){
6    super();
7   }
9  render(){
11    return (
12      <div className="App">
13             <h1>Welcome to App</h1>   
14      </div>
15    );
16  }

Using componentDidMount()

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

3    this.getUser();
4  }

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

1 constructor(){
2    super();
3    this.state={
4      users:[]
5    }
6  }

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.

1async getUser(){
2    let usersData=await axios.get('')
3                    .then(res=>{
4                      return;
5                    })
6                    .catch(err=>{
7                      console.log(err);
8                    })
9    this.setState({
10      users:usersData
11    },()=>{console.log(this.state)})
12  }

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

1  render(){
2    const {users}=this.state;
3    return (
4      <div className="App">
5        {users &&>{
6          return(
7            <div className="card" key={}>
8              <img src={user.avatar} alt="Avatar" style={{width:'auto'}}/>
9              <div className="container" >
10                <h4 ><b>{user.first_name}</b></h4>
11                <p>{}</p>
12              </div>
13            </div>
14          )
15        })}
17      </div>
18    );
19  }

Your App.js should look like this:

1import React,{Component} from 'react';
2import axios from 'axios';
4export default class App extends Component {
5  constructor(){
6    super();
7    this.getUser=this.getUser.bind(this);
8    this.state={
9      users:[]
10    }
11  }
12  componentDidMount(){
13    this.getUser();
14  }
15  async getUser(){
16    let usersData=await axios.get('')
17                    .then(res=>{
18                      return;
19                    })
20                    .catch(err=>{
21                      console.log(err);
22                    })
23    this.setState({
24      users:usersData
25    },()=>{console.log(this.state)})
26  }
27  render(){
28    const {users}=this.state;
29    return (
30      <div className="App">
31        {users &&>{
32          return(
33            <div className="card" key={}>
34              <img src={user.avatar} alt="Avatar" style={{width:'auto'}}/>
35              <div className="container" >
36                <h4 ><b>{user.first_name}</b></h4>
37                <p>{}</p>
38              </div>
39            </div>
40          )
41        })}
43      </div>
44    );
45  }

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.

1 componentDidUpdate(prevProps,prevState){
2    if( !=={
3      //make an API call here and update the state
4    }
5  }

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.


Inside the root directory, run:

1npm 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:

1import React,{useEffect,useState} from 'react';
2import axios from 'axios';
4export default function App () {
5  const[users,setUsers]=useState([]);
7  useEffect(async()=>{
8    let usersData=await axios.get('')
9                    .then(res=>{
10                      return;
11                    })
12                    .catch(err=>{
13                      console.log(err);
14                    })
15    setUsers(usersData)
16  },[])
18    return (
19      <div className="App">
20        {users &&>{
21          return(
22            <div className="card" key={}>
23              <img src={user.avatar} alt="Avatar" style={{width:'auto'}}/>
24              <div className="container" >
25                <h4 ><b>{user.first_name}</b></h4>
26                <p>{}</p>
27              </div>
28            </div>
29          )
30        })}
32      </div>
33    );


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.