Tips and Tricks #139: Optimize Re-renders with React.memo and useMemo

Prevent unnecessary component re-renders by memoizing components and computed values.

Code Snippet

import { memo, useMemo } from 'react';

// Memoize expensive child component
const ExpensiveList = memo(function ExpensiveList({ items }) {
  return (
    
    {items.map((item) => (
  • {item.name}
  • ))}
); }); // Parent component function Dashboard({ data, filter }) { // Memoize filtered results const filteredItems = useMemo( () => data.filter((item) => item.category === filter), [data, filter] ); return ; }

Why This Helps

  • Skips re-render when props haven’t changed
  • Prevents expensive recalculations
  • Improves responsiveness in complex UIs

How to Test

  • Use React DevTools Profiler to count renders
  • Add console.log in component to verify skipped renders

When to Use

Lists with many items, components with expensive render logic, frequently updating parents.

Performance/Security Notes

Don’t over-optimize. Profile first. memo() has its own overhead for simple components.

References


Try this tip in your next project and share your results in the comments!


Discover more from Code, Cloud & Context

Subscribe to get the latest posts sent to your email.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.