DEV Community

Vivek Lagshetti
Vivek Lagshetti

Posted on

๐Ÿš€ Optimizing React Performance with useMemo Hook (Real-Time Example)

When building React apps, performance optimization often feels like an afterthought โ€” until your app starts lagging. One common issue is expensive re-calculations happening on every render, even when theyโ€™re not needed.

In this post, Iโ€™ll show you a real-time example of how useMemo can help us optimize our app with proof by comparing two components:

  • Without useMemo โŒ โ†’ Filtering happens on every render
  • With useMemo โœ… โ†’ Filtering only happens when search changes

๐Ÿข Without useMemo

Hereโ€™s a simple example where we have 5,000 users and a search bar.

Every time we type something or even click a button unrelated to the search, React re-runs the filtering logic across all 5,000 users.

Without useMemo

๐Ÿ‘‰ Try clicking the Increase Count button โ€” even though it has nothing to do with the search, the filter runs again, wasting CPU cycles.

Without using useMemo

โšก With useMemo

Now, letโ€™s optimize it with useMemo.

Weโ€™ll memoize the filtered list so that React only recomputes when search changes, not when unrelated state (count) changes.

With useMemo

๐Ÿ‘‰ Now, open the console and try again. Youโ€™ll notice โ€œFiltering usersโ€ฆโ€ only logs when you change the search input, not when you click the button. ๐ŸŽ‰

With using useMemo

๐Ÿง  When to Use useMemo

โœ… Expensive computations (like filtering, sorting, complex calculations)

โœ… When you notice re-renders impacting performance

โœ… For lists, tables, or search-heavy components

โš ๏ธ Donโ€™t overuse it โ€” useMemo itself adds a small overhead. Use it where you know recalculations are costly.

๐Ÿš€ Key Takeaway

With just one hook (useMemo), we avoided unnecessary computations and made our app more efficient.

Performance optimizations like this might seem small, but at scale (large data, heavy UI), they make a huge difference.

๐Ÿ’ก What about you? Have you faced performance issues in your React apps? Did useMemo or useCallback help you fix them?

๐Ÿ‘‡ Drop your thoughts in the comments!

Top comments (0)