Melody Documentation
  • Why Melody?
  • Quickstart
    • What is Melody?
    • Tutorial
    • Installation
  • Templates
    • Twig
    • Mounting Components
    • Keys and Loops
    • Attributes
    • CSS Classes
    • Inline Styles
    • Refs
    • CSS Modules
  • Melody-Streams
    • Basic concept
    • A Step-by-Step Walkthrough
  • MELODY-STREAMS API
    • createComponent
    • The component function
  • melody-hooks
    • Overview
    • Rules of Hooks
    • Event Handling
    • Separation of Concerns
  • melody-hooks API
    • useState
    • useAtom
    • useEffect
    • useRef
    • useCallback
    • useMemo
    • useReducer
    • usePrevious
  • melody-component
    • Overview
  • melody-hoc
    • Overview
Powered by GitBook
On this page
  • Syntax
  • Storing an expensive computation

Was this helpful?

  1. melody-hooks API

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.

PrevioususeCallbackNextuseReducer

Last updated 5 years ago

Was this helpful?