Introduction
Rendering in React involves translating React components into a format that the browser can display. React employs a virtual DOM to make this process efficient, updating only the parts of the actual DOM that need to change. Let’s explore this in depth
What is Rendering?
Rendering in React involves creating a visual representation of the user interface (UI) by converting React components into DOM elements. React’s declarative approach enables developers to describe how the UI should look. Therefore, React takes care of updating the UI automatically when the underlying data changes.
Types of Rendering
React handles two primary types of rendering:
Initial Rendering
React renders a component and adds it to the DOM for the first time.
Re-Rendering
React updates a component whenever its state or props change.
Initial Rendering
Initial rendering occurs when a React component is first created and added to the DOM. During this phase, React builds the virtual DOM, compares it with the actual DOM, and updates the actual DOM to match the virtual DOM.
Example:
import React from 'react';
import ReactDOM from 'react-dom';
function App() {
return (
<div>
<h1>Hello, World!</h1>
</div>
);
}
ReactDOM.render(<App />, document.getElementById('root'));
Here, the App
component is rendered for the first time, displaying “Hello, World!” on the screen.
Re-Rendering and State Updates
Re-rendering happens when the component’s state or props change. Consequently, React re-renders the component by updating only the parts of the DOM that have changed, rather than re-rendering the entire component. This approach ensures efficiency and optimal performance.
Example with state updates:
import React, { useState } from 'react';
import ReactDOM from 'react-dom';
function App() {
const [count, setCount] = useState(0);
return (
<div>
<h1>Count: {count}</h1>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
ReactDOM.render(<App />, document.getElementById('root'));
Clicking the “Increment” button updates the count
state, causing the component to re-render with the new count value.
Conditional Rendering
Conditional rendering allows you to render different UI elements based on certain conditions, making your UI dynamic and interactive.
Example:
function App() {
const [isLoggedIn, setIsLoggedIn] = useState(false);
return (
<div>
{isLoggedIn ? <h1>Welcome back!</h1> : <h1>Please log in.</h1>}
<button onClick={() => setIsLoggedIn(!isLoggedIn)}>
{isLoggedIn ? 'Logout' : 'Login'}
</button>
</div>
);
}
In this example, the message and button text change based on the isLoggedIn
state.
List Rendering
List rendering is essential when dealing with dynamic data. React efficiently handles list rendering using the map
function.
Example:
function App() {
const items = ['Apple', 'Banana', 'Cherry'];
return (
<ul>
{items.map((item, index) => (
<li key={index}>{item}</li>
))}
</ul>
);
}
This example renders a list of items as list elements.
Using Keys in Lists
Keys play an important role in list rendering because they help React identify which items have changed, been added, or removed. Ensure keys are unique and stable.
Example with unique keys:
function App() {
const items = [
{ id: 1, name: 'Apple' },
{ id: 2, name: 'Banana' },
{ id: 3, name: 'Cherry' },
];
return (
<ul>
{items.map((item) => (
<li key={item.id}>{item.name}</li>
))}
</ul>
);
}
Understanding the Virtual DOM
The virtual DOM is a lightweight representation of the actual DOM. React keeps a virtual DOM to optimize the rendering process. When the state or props of a component change, React updates the virtual DOM first, compares it with the previous version, and then updates only the necessary parts of the actual DOM. This process is called reconciliation.
Example: Building a Real-Time Todo App
Let’s build a more comprehensive example to illustrate the concepts we’ve covered. We’ll create a real-time Todo app where users can add, remove, and update todo items.
import React, { useState } from 'react';
import ReactDOM from 'react-dom';
function TodoApp() {
const [todos, setTodos] = useState([]);
const [input, setInput] = useState('');
const addTodo = () => {
if (input.trim() !== '') {
setTodos([...todos, { id: Date.now(), text: input }]);
setInput('');
}
};
const removeTodo = (id) => {
setTodos(todos.filter(todo => todo.id !== id));
};
return (
<div>
<h1>Todo List</h1>
<input
type="text"
value={input}
onChange={(e) => setInput(e.target.value)}
/>
<button onClick={addTodo}>Add Todo</button>
<ul>
{todos.map((todo) => (
<li key={todo.id}>
{todo.text}
<button onClick={() => removeTodo(todo.id)}>Remove</button>
</li>
))}
</ul>
</div>
);
}
ReactDOM.render(<TodoApp />, document.getElementById('root'));

In this example:
- Users can add a new todo by typing into the input field and clicking “Add Todo”.
- Each todo item is displayed in a list with a unique key.
- Users can remove a todo by clicking the “Remove” button next to the respective item.
Conclusion
Rendering in React is a fundamental concept that enables the creation of dynamic and efficient user interfaces. By understanding initial rendering, re-rendering, conditional rendering, list rendering, the use of keys, and the virtual DOM, you can build powerful React applications. The real-time Todo app example demonstrates how these concepts work together to create a functional and interactive application.
No Comment! Be the first one.