Re-rendering Components in ReactJS
In ReactJS, re-rendering occurs when React needs to update the app with new data or when a component’s state or props change. React compares the updated component with the previous one and updates only the parts that need changing to keep everything in sync.
How React Handles Re-Rendering
React uses Virtual DOM as an intermediate layer. It sits between what the developer wants to show on the screen and what the browser actually renders. This helps React efficiently update only the necessary parts of the UI.
- Initial Render: React creates a virtual DOM tree representing the UI based on the current state and props of components.
2.State or Props Change: When the state or props change, React updates the component’s virtual DOM and compares it with the previous virtual DOM using a process called reconciliation.
3.Diffing Algorithm: React’s diffing algorithm identifies the differences between the current and previous virtual DOM. Only the changes are applied to the real DOM, which minimizes performance overhead.
4.Re-rendering: React re-renders the components with the new state or props, and only the necessary DOM updates are applied.
Example: React Re-rendering with State
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
export default Counter;
Output
In this example
Initially the component rerenders with the count = 0.
When we click the button the state updates, which trigger the re-rendering.
Now, the React will compare with the virtual Dom and will update the only changed part.
Reference
https://www.geeksforgeeks.org/reactjs/re-rendering-components-in-reactjs/

Top comments (0)