useMemo

Syntax

useMemo(computation: Function, cacheKeyProperties: Array<Any>): Any

The useMemo hook allows you to persist computed values across state hook evaluations. It is very similar to useCallback but, when needed, it'll execute the function passed to it and return the computed value.

Storing an expensive computation

function useSlug({ text }) {
    const slug = useMemo(() => slugify(text), [text]);
    return slug;
}

In the above example, we memoize the call to an expensive slugify function, which will translate a string such as "Separation of Concerns" to "separation-of-concerns". useMemo enables us to avoid recomputing that value until the text we wanted to slugify actually changed.

As with useCallback and useEffect you should always try to minimise dependencies, however, due to the nature of useMemo, you'll want to depend on values instead of accessor functions, just like with useEffect.

Last updated

Was this helpful?