Sobes.tech
Middle+

Tell about optimization of rendering in React.

sobes.tech AI

Answer from AI

Rendering optimization in React aims to reduce the number of re-renders and speed up their execution.

Main approaches:

  • Memoization (React.memo, useMemo, useCallback):

    • React.memo(): Wraps a functional component and prevents it from re-rendering if props haven't changed (shallow comparison).
      // Example with React.memo
      const MyComponent = React.memo(function MyComponent(props) {
        // ...render content
      });
      
    • useMemo(): Memoizes a value (computation result), recalculating it only when dependencies change.
      // Example with useMemo
      const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
      
    • useCallback(): Memoizes a callback function, preventing its recreation on every parent re-render. Useful for passing callbacks to memoized child components.
      // Example with useCallback
      const handleClick = useCallback(() => {
        // ...handler logic
      }, [dependency1, dependency2]);
      
  • List optimization (Keys): Using unique key for list items helps React efficiently update the DOM by identifying which items have been added, removed, or changed.

    // Example with keys
    <ul>
      {items.map(item => (
        <li key={item.id}>{item.text}</li>
      ))}
    </ul>
    
  • Lazy loading components (React.lazy, Suspense): Code splitting allows loading components only when needed, reducing the initial bundle size. React.lazy is used for dynamic import, and Suspense for displaying fallback UI during loading.

    // Example with React.lazy and Suspense
    const OtherComponent = React.lazy(() => import('./OtherComponent'));
    
    function MyPage() {
      return (
        <Suspense fallback={<div>Loading...</div>}>
          <OtherComponent />
        </Suspense>
      );
    }
    
  • List virtualization (React-Window, React-Virtualized): For very long lists, only the visible part is rendered, not the entire list at once, significantly improving rendering performance.

  • Avoid unnecessary state updates: Combining state updates, using functional setState in class components, or directly using the current state in hooks (setState(prevState => ...)) helps prevent unnecessary re-renders.

  • Using PureComponent (for class components): Similar to React.memo for functional components, PureComponent performs a shallow comparison of props and state, preventing unnecessary re-renders.

  • Minimize logic in render/functional component body: Complex calculations are better moved to useMemo or outside of render.

  • Profiling: Using React Developer Tools Profiler helps identify bottlenecks in rendering.