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. "Hello, World!" Program in ReactJavaScriptimport React from 'react'; function App() {
6 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 DOM-specific methods to interact with and manipulate the Document Object Model (DOM), enabling efficient rendering and management of web page elements. ReactDOM is used for: Rendering Components: Displays React components in the DOM.DOM Manipulation: Al
2 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 ListsIn lists, React makes it easier to render multiple elements dynamically from arrays or objects, ensuring efficient and reusable code. Since nearly 85% of React projects involve displaying data collectionsâlike user profiles, product catalogs, or tasksâunderstanding how to work with lists.To render a
4 min read
React FormsIn React, forms are used to take input from users, like text, numbers, or selections. They work just like HTML forms but are often controlled by React state so you can easily track and update the input values.Example:JavaScriptimport React, { useState } from 'react'; function MyForm() { const [name,
4 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. When rendering a list, you need to assign a unique key prop to each element in th
4 min read
Components in React
React ComponentsIn React, components are reusable, independent code blocks (A function or a class) that define the structure and behavior of the UI. They accept inputs (props or properties) and return elements that describe what should appear on the screen.Key Concepts of React Components:Each component handles its
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.Example:JavaScriptimport
4 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
3 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.Type Safety: When the wrong data type is passed in the component, prototypes help find the issues.Better Debugging: During development, t
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