DEV Community

Cover image for How to Optimize React Apps with Memoization and Custom Comparison Functions
HexShift
HexShift

Posted on • Edited on

How to Optimize React Apps with Memoization and Custom Comparison Functions

As your React application scales, unnecessary re-renders can hurt performance. React's built-in React.memo and custom comparison functions allow you to fine-tune rendering behavior. In this guide, we'll explore how to use memoization efficiently in real-world scenarios, especially with complex props.

1. React.memo Basics

React.memo is a higher-order component that prevents re-renders when props haven't changed:

const Greeting = React.memo(function Greeting({ name }) {
  console.log("Rendered Greeting");
  return <p>Hello, {name}!</p>;
});

If the parent component re-renders but the name prop is unchanged, Greeting won’t re-render.

2. Custom Comparison Functions

When props are complex (e.g., objects or arrays), React compares them by reference. You can provide your own comparison function:

const ExpensiveComponent = React.memo(function ExpensiveComponent({ data }) {
  return <div>{data.title}</div>;
}, (prevProps, nextProps) => {
  return prevProps.data.id === nextProps.data.id;
});

This ensures re-renders only occur when necessary—even if the object reference changes but its relevant data hasn’t.

3. Memoizing Callbacks With useCallback

Passing inline functions as props can also trigger re-renders. Use useCallback to memoize them:

const handleClick = useCallback(() => {
  console.log("Clicked");
}, []);

4. Memoizing Values With useMemo

To avoid recalculating expensive operations:

const sortedData = useMemo(() => {
  return data.sort((a, b) => a.value - b.value);
}, [data]);

5. When Not to Memoize

  • Components that render infrequently or are lightweight don’t benefit from memoization.
  • Overusing memo can lead to more complex and harder-to-maintain code.

Pros & Cons of Memoization in React

  • ✅ Pros:
    • Reduces unnecessary rendering of child components
    • Improves performance in list-heavy UIs
    • Fine-grained control via custom comparison functions
  • ⚠️ Cons:
    • Can increase memory usage due to retained closures
    • Requires careful tracking of dependencies
    • Added complexity if overused

Alternatives

  • Virtualization (e.g., react-window) for huge lists
  • Context selectors for slicing data at consumption points
  • State colocation to reduce prop drilling and renders

Conclusion

Memoization is a powerful tool for performance-sensitive React apps. When used strategically, React.memo, useCallback, and useMemo can significantly reduce re-renders without sacrificing readability.

For a much more extensive guide on getting the most out of React portals, check out my full 24-page PDF file on Gumroad. It's available for just $10:

Using React Portals Like a Pro.

If this post helped you, consider supporting me: buymeacoffee.com/hexshift

Top comments (0)