React Performance Optimization

While React is fast by default, unnecessary re-renders can slow down your application. Optimizing performance involves making sure components only re-render when absolutely necessary.

1. React.memo

React.memo is a higher-order component that memoizes a component. If its props haven't changed, React will skip rendering the component and reuse the last rendered result.

JavaScript

import React from 'react';

const MyComponent = React.memo(function MyComponent(props) {
  /* render using props */
  return <div>{props.name}</div>;
});          

2. useMemo

As covered in Advanced Hooks, useMemo memoizes the result of a calculation. It is useful for avoiding expensive computations on every render.

JavaScript

const expensiveResult = useMemo(() => {
  return performHeavyCalculation(data);
}, [data]);          

3. Virtualization for Large Lists

When rendering thousands of rows, the DOM can become a bottleneck. Windowing or Virtualization only renders the items currently visible to the user, significantly improving performance.

Note:Premature optimization is the root of all evil. Only apply these techniques if you notice performance issues or after profiling your app.