DEV Community

Kenneth Lum
Kenneth Lum

Posted on

5 1

The useMemo() hook in ReactJS has a short memory

The useMemo() hook in React as of 16.8.0 can memoized a value for an expensive computation, but note that it has really "short memory".

To see how it works, look at the "console" to see when the expensive function is invoked: https://stackblitz.com/edit/react-ueeptk

The code:

  const value = useMemo(() => expensiveFunction(a), [a]);
Enter fullscreen mode Exit fullscreen mode

When it already did the calculation for a being 2, then it won't do it for 2 next time. Likewise for the 3 or 4.

However, it really can only memoize one value. If the first time, it did the calculation for 1, and next it did the calculation for 2, it won't remember what the result is for 1 any more. When supplied with 1 again, it will do the calculation again. Example: https://stackblitz.com/edit/react-hpugxu

The behavior is similar to React.memo(ComponentA), which can memoize a function component result and won't call it to render the React elements again as long as the props, state, and context stay the same.

Image of Datadog

The Future of AI, LLMs, and Observability on Google Cloud

Datadog sat down with Google’s Director of AI to discuss the current and future states of AI, ML, and LLMs on Google Cloud. Discover 7 key insights for technical leaders, covering everything from upskilling teams to observability best practices

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more