Sobes.tech
Middle+

How to avoid unnecessary re-renders in React?

sobes.tech AI

Answer from AI

To avoid unnecessary re-renders in React, you can use several approaches:

  • React.memo — wraps a functional component and prevents re-rendering if props haven't changed.
  • useMemo — memoizes computed values to avoid recalculating them on every render.
  • useCallback — memoizes functions to prevent creating new references and triggering re-renders of child components.
  • PureComponent — for class components, automatically implements shouldComponentUpdate with shallow comparison of props and state.
  • Avoid creating new objects and functions inside render, as this leads to reference changes and triggers re-rendering.

Example with React.memo and useCallback:

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

const Child = React.memo(({ onClick }) => {
  console.log('Child rendered');
  return <button onClick={onClick}>Click me</button>;
});

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

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

  return (
    <div>
      <p>Count: {count}</p>
      <Child onClick={handleClick} />
    </div>
  );
}

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

How to avoid unnecessary re-renders in React… - sobes.tech