Optimizing rendering performance in React

Re-render happens when React needs to update the app with some new data. Usually, this happens as a result of a user interacting with the app or some external data coming through via an asynchronous request or some subscription model.

How React Handles Re-Rendering?

React uses the Virtual DOM for handling the re-rendering:

  1. 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.

When React component re-redeners itself?

Its state change (includes redux):

Using setState in class components or useState in functional components triggers a re-render.

Props change:

When a parent component passes new props to a child, the child component re-renders

Force update:

Although rarely needed, you can force a re-render using forceUpdate() in class components.

Its parent component re-render:

Component will re-render itself if its parent re-renders. Or, if we look at this from the opposite direction: when a component re-renders, it also re-renders all its children.

Context change:

Components consuming context via useContext will re-render when the context value changes.


How to prevent unnecessary re-render ?

useMemo

useMemo is a React Hook that lets you cache the result of a calculation between re-renders.

useCallback

useCallback is a React Hook that lets you cache a function definition between re-renders.

React.memo

Wrap a component in memo to get a memoized version of that component. This memoized version of your component will usually not be re-rendered when its parent component is re-rendered as long as its props have not changed. But React may still re-render it: memoization is a performance optimization, not a guarantee.

shouldComponentUpdate lifecycle

Use shouldComponentUpdate() to let React know if a component’s output is not affected by the current change in state or props. The default behavior is to re-render on every state change, and in the vast majority of cases you should rely on the default behavior.


Conclusion

React re-render is an important process to understand for React developers. Preventing unnecessary re-renders is necessary for optimizing React app performance and efficiently utilizing resources.