Sobes.tech
Middle

What are the ways to optimize performance in React?

sobes.tech AI

Answer from AI

To optimize performance in React, the following approaches can be used:

  • Component memoization using React.memo to prevent unnecessary re-renders.
  • Using hooks useMemo and useCallback to cache computations and functions.
  • Splitting the application into small components for localized updates.
  • Lazy loading components (React.lazy and Suspense) to reduce initial load time.
  • Optimizing list rendering with key and virtualization (e.g., react-window).
  • Avoiding unnecessary state updates and managing state properly.

Example of using React.memo:

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

function App() {
  const [count, setCount] = React.useState(0);
  const increment = () => setCount(c => c + 1);

  return (
    <div>
      <Button onClick={increment} label="Click me" />
      <p>Counter: {count}</p>
    </div>
  );
}

Here, Button will not re-render unless its props change, which saves resources.