Quiz

What does re-rendering mean in React?

Topics
React
在GitHub上编辑

TL;DR

Re-rendering in React refers to the process where a component updates its output to the DOM in response to changes in state or props. When a component's state or props change, React triggers a re-render to ensure the UI reflects the latest data. This process involves calling the component's render method again to produce a new virtual DOM, which is then compared to the previous virtual DOM to determine the minimal set of changes needed to update the actual DOM.


What does re-rendering mean in React?

Understanding re-rendering

Re-rendering in React is the process by which a component updates its output to the DOM in response to changes in its state or props. This ensures that the UI is always in sync with the underlying data.

When does re-rendering occur?

Re-rendering occurs in the following scenarios:

  • When a component's state changes using setState
  • When a component receives new props from its parent component
  • When the parent component re-renders, causing its child components to re-render as well

The re-rendering process

  1. State or props change: When a component's state or props change, React schedules a re-render for that component.
  2. Render method: React calls the component's render method to generate a new virtual DOM tree.
  3. Virtual DOM comparison: React compares the new virtual DOM tree with the previous one using a diffing algorithm.
  4. DOM updates: React calculates the minimal set of changes required and updates the actual DOM accordingly.

Example

Here's a simple example to illustrate re-rendering:

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>
);
}

In this example:

  • The Counter component has a state variable count.
  • When the button is clicked, setCount updates the state, triggering a re-render.
  • The render method is called again, and the new virtual DOM is compared to the previous one.
  • React updates the actual DOM to reflect the new count.

Performance considerations

Re-rendering can be expensive, especially for complex components or large applications. To optimize performance, React provides several techniques:

  • PureComponent: A base class that implements a shallow comparison of props and state to prevent unnecessary re-renders.
  • React.memo: A higher-order component that memoizes the result of a component's render to avoid re-rendering if the props haven't changed.
  • useMemo and useCallback: Hooks that memoize values and functions to prevent unnecessary re-renders.

Further reading

在GitHub上编辑