In React, lifecycle methods manage a component’s behaviour at different stages. The render() method is important for defining the UI, updating it whenever state, props, or context changes, and ensuring the UI stays in sync with the component’s data.
What is the Render() Method in ReactJS?
The render() method is an essential part of React class components that determines what gets displayed on the user interface (UI). It plays a key role in rendering elements and updating the UI dynamically.
- The render() method in React is the lifecycle method.
- The render() method gets called automatically.
- It must return JSX or null.
- It cannot mutate state.
- The logic and the calculation should be written and performed outside the render() method.
Syntax
class MyComponent extends React.Component {
render() {
return <h1>Hello, World!</h1>;
}
}
How do render() Work?
The render() method is called every time React determines that a component’s state or props have changed. When this happens, React re-renders the component, calling the render() method to generate a new version of the UI.
Here’s a basic example of how the render() method works
JavaScript
import React, { Component } from 'react';
class Welcome extends Component {
render() {
return <h1>Hello, {this.props.name}!</h1>;
}
}
export default Welcome;
Output
React.JS render() MethodIn the example above
- Welcome is a class-based component.
- The render() method returns a simple JSX element, which displays the name prop passed to the component.
- Every time the name prop changes, the render() method will be triggered again to reflect the updated name in the UI.
Implementing render() Method
This React class component, Greeting, uses state to conditionally render a welcome message or login prompt based on the user's login status.
JavaScript
import React, { Component } from 'react';
class Greeting extends Component {
constructor(props) {
super(props);
this.state = {
name: 'Anjali', // Initial state
isLoggedIn: true,
};
}
render() {
// Conditional rendering based on state
if (this.state.isLoggedIn) {
return (
<div>
<h1>Welcome back, {this.state.name}!</h1>
<button onClick={() => this.setState({ isLoggedIn: false })}>Log out</button>
</div>
);
} else {
return (
<div>
<h1>Please log in.</h1>
<button onClick={() => this.setState({ isLoggedIn: true })}>Log in</button>
</div>
);
}
}
}
export default Greeting;
Output:
Render() MethodIn this example
- The constructor() method initializes the component’s state with name and isLoggedIn properties.
- The render() method is responsible for returning JSX based on the component’s state.
- If isLoggedIn is true, it shows a welcome message and a "Log out" button.
- If isLoggedIn is false, it shows a "Please log in." message and a "Log in" button.
- The onClick event handlers on the buttons call this.setState() to toggle the isLoggedIn state, which triggers the re-render of the component.
In React 18, the render() method is replaced by the createRoot. Using the render method in react 18 will show a warning, and your app will work like it's still using React 17, not taking advantage of new features in React 18. To use React 18 features, you should use createRoot() instead of render().
Interesting Fact about the ReactJS render() Method
- Returns Virtual DOM, Not Real DOM: The render() method does not modify the real DOM directly. It updates the Virtual DOM, and React efficiently updates only the necessary changes.
class MyComponent extends React.Component {
render() {
return <h1>Hello, Virtual DOM!</h1>;
}
}
- Triggers Reconciliation Process: React compares the old Virtual DOM with the new one and updates only the changed parts, improving performance.
- Must Return a Single Parent Element: The render() method must return a single parent element. Use <div> or <React.Fragment> if needed.
class MyComponent extends React.Component {
render() {
return (
<>
<h1>Title</h1>
<p>Description</p>
</>
);
}
}
- Should Be a Pure Function: render() should be a pure function, meaning it should not modify state directly to avoid infinite loops.
render() {
this.setState({ count: this.state.count + 1 }); // Wrong!
return <h1>Count: {this.state.count}</h1>;
}
Correct Approach: Use Event Handlers or Lifecycle Methods
componentDidMount() {
this.setState({ count: this.state.count + 1 });
}
- Triggers Automatically on State or Prop Changes:
When setState() or new props are received, render() is called again automatically.
class Message extends React.Component {
render() {
return <h1>{this.props.text}</h1>;
}
}
<Message text="Hello, React!" /> // Changing props will trigger re-render
Incorrect: Async render() (Will Cause an Error)
async render() {
const data = await fetchData(); // Wrong
return <h1>{data}</h1>;
}
Correct Approach: Use componentDidMount()
componentDidMount() {
fetch("https://api.example.com/data")
.then(response => response.json())
.then(data => this.setState({ data }));
}
render() in Functional Component (Not exist explicity)
In functional components, the render() method does not exist explicitly. Instead, the component itself is a function that returns JSX. When state or props change, React automatically re-renders the component, and the function is called again to return the updated JSX.
JavaScript
import React, { useState } from 'react';
const Greeting = () => {
const [isLoggedIn, setIsLoggedIn] = useState(true);
const [name, setName] = useState('Anjali');
return (
<div>
{isLoggedIn ? (
<>
<h1>Welcome back, {name}!</h1>
<button onClick={() => setIsLoggedIn(false)}>Log out</button>
</>
) : (
<>
<h1>Please log in.</h1>
<button onClick={() => setIsLoggedIn(true)}>Log in</button>
</>
)}
</div>
);
};
export default Greeting;
Output:
Functional Component In this example the render() method is not used, it has returned the JSX directly.
In a functional component, there is no separate "render" method because the function itself acts as the render method and they directly returns the JSX but in the class components we define a render method within the class,
Purpose of render() Method
- The render() method defines how the component's UI should appear on the screen.
- It returns JSX, which is a combination of HTML and JavaScript used to describe the component’s structure.
- The method runs automatically every time the component’s state or props change, updating the UI accordingly.
- It ensures that the component's content is always in sync with its state and the data it receives.
Similar Reads
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
React Fundamentals
React IntroductionReactJS is a component-based JavaScript library used to build dynamic and interactive user interfaces. It simplifies the creation of single-page applications (SPAs) with a focus on performance and maintainability.React.jsWhy Use React?Before React, web development faced issues like slow DOM updates
7 min read
React Environment SetupTo run any React application, we need to first setup a ReactJS Development Environment. In this article, we will show you a step-by-step guide to installing and configuring a working React development environment.Pre-requisite:We must have Nodejs installed on our PC. So, the very first step will be
3 min read
React JS ReactDOMReactDom is a core react package that provides methods to interact with the Document Object Model or DOM. This package allows developers to access and modify the DOM. Let's see in brief what is the need to have the package. Table of ContentWhat is ReactDOM ?How to use ReactDOM ?Why ReactDOM is used
3 min read
React JSXJSX stands for JavaScript XML, and it is a special syntax used in React to simplify building user interfaces. JSX allows you to write HTML-like code directly inside JavaScript, enabling you to create UI components more efficiently. Although JSX looks like regular HTML, itâs actually a syntax extensi
5 min read
ReactJS Rendering ElementsIn this article we will learn about rendering elements in ReactJS, updating the rendered elements and will also discuss about how efficiently the elements are rendered.What are React Elements?React elements are the smallest building blocks of a React application. They are different from DOM elements
3 min read
React ListsReact Lists are used to display a collection of similar data items like an array of objects and menu items. It allows us to dynamically render the array elements and display repetitive data.Rendering List in ReactTo render a list in React, we will use the JavaScript array map() function. We will ite
5 min read
React FormsForms are an essential part of any application used for collecting user data, processing payments, or handling authentication. React Forms are the components used to collect and manage the user inputs. These components include the input elements like text field, check box, date input, dropdowns etc.
5 min read
ReactJS KeysA key serves as a unique identifier in React, helping to track which items in a list have changed, been updated, or removed. It is particularly useful when dynamically creating components or when users modify the list. In this article, we'll explore ReactJS keys, understand their importance, how the
5 min read
Components in React
React ComponentsIn React, React components are independent, reusable building blocks in a React application that define what gets displayed on the UI. They accept inputs called props and return React elements describing the UI.In this article, we will explore the basics of React components, props, state, and render
4 min read
ReactJS Functional ComponentsIn ReactJS, functional components are a core part of building user interfaces. They are simple, lightweight, and powerful tools for rendering UI and handling logic. Functional components can accept props as input and return JSX that describes what the component should render.What are Reactjs Functio
5 min read
React Class ComponentsClass components are ES6 classes that extend React.Component. They allow state management and lifecycle methods for complex UI logic.Used for stateful components before Hooks.Support lifecycle methods for mounting, updating, and unmounting.The render() method in React class components returns JSX el
4 min read
ReactJS Pure ComponentsReactJS Pure Components are similar to regular class components but with a key optimization. They skip re-renders when the props and state remain the same. While class components are still supported in React, it's generally recommended to use functional components with hooks in new code for better p
4 min read
ReactJS Container and Presentational Pattern in ComponentsIn this article we will categorise the react components in two types depending on the pattern in which they are written in application and will learn briefly about these two categories. We will also discuss about alternatives to this pattern. Presentational and Container ComponentsThe type of compon
2 min read
ReactJS PropTypesIn ReactJS PropTypes are the property that is mainly shared between the parent components to the child components. It is used to solve the type validation problem. Since in the latest version of the React 19, PropeTypes has been removed. What is ReactJS PropTypes?PropTypes is a tool in React that he
5 min read
React Lifecycle In React, the lifecycle refers to the various stages a component goes through. These stages allow developers to run specific code at key moments, such as when the component is created, updated, or removed. By understanding the React lifecycle, you can better manage resources, side effects, and perfo
7 min read
React Hooks
Routing in React
Advanced React Concepts
React Projects