Quay lại TIL
2023-06-15Frontendintermediate3 min

Optimizing React Renders


# Optimizing React Renders

React's rendering process can sometimes lead to performance issues, especially in larger applications. Today I learned about three key methods to optimize rendering:

## React.memo

React.memo is a higher-order component that memoizes the rendered output of the wrapped component, preventing unnecessary re-renders if the props haven't changed.

## useCallback

The useCallback hook returns a memoized version of the callback function that only changes if one of the dependencies has changed. This is useful when passing callbacks to optimized child components that rely on reference equality to prevent unnecessary renders.

## useMemo

Similar to useCallback, useMemo memoizes the result of a computation and only recomputes it when one of its dependencies changes. This is particularly useful for expensive calculations.

By implementing these techniques strategically, I was able to reduce render times in a complex dashboard component by nearly 40%.

Code Example

const MemoizedComponent = React.memo(function MyComponent(props) {
  // Only re-renders if props change
});

const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
const memoizedCallback = useCallback(() => doSomething(a, b), [a, b]);
ReactPerformanceOptimization