Urgent.News

What's breaking now, across thousands of outlets.

Tech

Understanding useMemo and useCallback

Understanding useMemo and useCallback can seem daunting at first, but they are essential hooks in React for optimizing performance. useMemo allows us to "remember" a computed value between renders, which can prevent unnecessary calculations and improve application performance.

Imagine a scenario where an application needs to compute a list of prime numbers based on a user-specified number. If the user selects a large number, the application will need to perform numerous computations, which can be time-consuming. This can lead to performance issues, especially if the user performs other actions while waiting for the results.

Memoization, which is what useMemo does, is a technique used to cache the results of expensive function calls and return the cached result when the same inputs occur again. In our example, useMemo can be used to cache the list of prime numbers. The dependencies passed to useMemo act as an invalidation strategy. If the dependencies (like selectedNum) change, useMemo will recalculate the primes; otherwise, it will reuse the previously calculated value.

This can be particularly useful in scenarios where the same expensive function is called multiple times with the same arguments. However, it's not always the best solution. Sometimes, restructuring the application to push state down rather than lifting it up can avoid the need for useMemo. This involves breaking down the application into smaller components, each managing their own state.

In the provided example, the App component was managing both the selectedNum and time states, leading to unnecessary re-calculations. By separating these states into their own components, Clock and PrimeCalculator, we can avoid this issue. This approach promotes a more modular and maintainable codebase, even if it's not always the optimal solution.

Written by urgent.news from Lobsters's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.

Read the original at joshwcomeau.com →

More in Tech

Nobody Argued For Your Stack

Last week, it came to light Cursor had mostly finished migrating from SolidJS to React . This migration happened about seven months ago.

  • Cursor completed SolidJS to React migration seven months prior to discovery.
  • Anthropic's migration feature example present since April 2026.
  • Cursor blog post criticized performance issues without providing data.

More from Thursday 27 August →