render() in ReactJS

render() method in component is called when component is about to mount to DOM and everytime when state object of component gets updated ( by setState() ). So in both stages Mounting phase of component and Updating phase of component.

This is the required method for class component ( stateful component ). Other lifecycle methods can be added as per requirement.

Why render() should be used?

render() method returns JSX element which will ultimatly added to DOM. In other words, render() method returns UI of the component.

Most of the times, you will be returning JSX element but it is not necessary to return JSX element. It can return one of the followings.

Let us have a look at an example.


import React from 'react';
import ReactDOM from 'react-dom';

class NumberComp extends React.Component{
  render(){
    return (
      3
    );
  }
}

class StringComp extends React.Component{
  render(){
    return (
      "This is string"
    );
  }
}

class HtmlComp extends React.Component{
    render(){
        return (
            <h1>
                This is React Application.
            </h1>
        );
    }
}

class App extends React.Component{
  render(){
    return (
      <React.Fragment>
        <NumberComp />
        <br />
        <StringComp />
        <HtmlComp />
      </React.Fragment>
    );
  }
}

ReactDOM.render(
    <App />,
    document.getElementById('root')
);
                    

Open above code in codepen.

In above example, render() method returns Number, String, HTML element and React.Fragment.

Points to remember while using render()

render() method uses state and props object and returns the UI for component. There are some points that you should remember while using render() method.

  • render() method should not change state object. Because when you change the state object, it will call render() method which will again call render() which will create infinite loop.
  • render() method should not interact with browser or interact with DOM. You can do that in componentDidMount.
  • You should not fetch any data in render() method. render() method is pure method. So any thing that creates side effects should not be done in render() method.

Conclusion

In this section, we learned about render() method and for what it can be used.
In the next section, you will learn about componentDidMount() method of ReactJS component.