Sobes.tech
Middle+

How do you optimize in React?

sobes.tech AI

Answer from AI

React optimization includes several approaches to improve performance and reduce unnecessary re-renders:

  • Using React.memo for memoizing functional components to prevent re-renders when props haven't changed.

  • useCallback and useMemo help memoize functions and calculations to avoid creating new objects and functions on each render.

  • Splitting into smaller components to localize changes and reduce the re-rendering area.

  • Lazy loading components (React.lazy and Suspense) to decrease the initial bundle size.

  • List optimization with key and virtualization (e.g., react-window) for efficient rendering of large lists.

  • Avoiding anonymous functions and objects in props to prevent unnecessary child component re-renders.

  • Profiling with React DevTools Profiler to identify bottlenecks.

Example of using React.memo and useCallback:

import React, { useState, useCallback } from 'react';

const Button = React.memo(({ onClick, children }) => {
  console.log('Button rendered');
  return <button onClick={onClick}>{children}</button>;
});

function Counter() {
  const [count, setCount] = useState(0);

  const increment = useCallback(() => {
    setCount(c => c + 1);
  }, []);

  return (
    <div>
      <p>Count: {count}</p>
      <Button onClick={increment}>Increment</Button>
    </div>
  );
}

Here, the Button will not re-render unnecessarily because onClick is memoized.