![]() |
VOOZH | about |
In React, lifecycle methods control a component’s behavior at different stages, and the render() method defines what appears on the UI and keeps it updated whenever state, props, or context change.
Syntax
class MyComponent extends React.Component {
render() {
return <h1>Hello, World!</h1>;
}
}
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
Output
In the example above
This React class component, Greeting, uses state to conditionally render a welcome message or login prompt based on the user's login status.
Output:
In this example
In React 18,
ReactDOM.render()is replaced bycreateRoot(). Using it triggers a warning and runs your app in React 17 compatibility mode, so you should usecreateRoot()to access new features.
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.
Output:
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,
class MyComponent extends React.Component {
render() {
return <h1>Hello, Virtual DOM!</h1>;
}
}
class MyComponent extends React.Component {
render() {
return (
<>
<h1>Title</h1>
<p>Description</p>
</>
);
}
}
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 });
}
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-renderIncorrect: 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 }));
}