Skip to content

use_memo

use_memo keeps a value from one render to the next, computing it again only when its dependencies change. Use it for:

  • An expensive value derived from arguments or state, such as a sorted or filtered list.
  • An unchanging part of a component's output. A component that returns the same element object as last render keeps the components inside it from re-running.
  • A handler passed to a memo component. A handler defined inline is a new object every render, so the memo component's arguments never equal last render's.
@component
def file_list(paths: tuple[str, ...]) -> Div:
    use_focus(auto_focus=True)
    descending, set_descending = use_state(False)

    ordered = use_memo(lambda: sorted(paths, reverse=descending), deps=(paths, descending))

    def on_input(event: InputEvent, _: Receiver) -> InputResponse:
        match event:
            case KeyPressed(key="r"):
                set_descending(toggle)
                return ()
            case _:
                return None

    return Div(
        style=col,
        on_input=on_input,
        children=(
            Text(content=f"{'Z to A' if descending else 'A to Z'} (r reverses)", style=text_color("slate", 400)),
            *(Text(content=path) for path in ordered),
        ),
    )


@component
def browser() -> Div:
    tick = use_clock(timedelta(seconds=1))
    seconds = tick.since_mount // timedelta(seconds=1)

    return Div(
        style=col | border | border_lightrounded | pad_x(1),
        children=(
            Text(content=f"Open for {seconds} s", style=text_color("amber", 400)),
            file_list(PATHS),
        ),
    )

A file browser open for 12 seconds, listing five paths from Z to A

╭────────────────────────────╮
│ Open for 12 s              │
│ Z to A (r reverses)        │
│ tests/test_app.py          │
│ src/app.py                 │
│ pyproject.toml             │
│ mkdocs.yml                 │
│ docs/index.md              │
╰────────────────────────────╯

browser re-runs every second to show how long it's been open, and each of those renders re-runs file_list with it (see Which components run in a frame?). file_list sorts paths again only when paths or descending changes, as pressing r did above, not on every render its parent causes.

A handler to keep stable is use_memo(lambda: handler, deps).

Dependencies

deps has to list every value compute reads that can change between renders: arguments, state, and anything computed from them. A value left out keeps the cached result from updating when it changes. For a cached handler, that means the handler keeps acting on the value it captured when it was cached. When a handler only needs the latest state to compute the next state, pass a function to the setter (set_count(lambda count: count + 1)), which needs no dependency on count.

Since hooks are found by their position, use_memo can't be called once per item in a loop whose length can change. To cache something per item, render a component per item and call use_memo in it, or declare that component memo.

Passing check_purity=True to app in tests catches a missing dependency: each use_memo whose deps didn't change also calls compute, and raises StaleMemo if the result differs from the cached value. Handlers are compared by their code and the values they captured, as in Keeping components pure.

use_memo or functools.lru_cache?

Both cache a computed value, but they differ in who owns it. A use_memo value belongs to one mounted component. An lru_cache value belongs to a function, and every caller in the process shares it. So cache a pure function of its arguments with lru_cache, and use use_memo for a value that belongs to the component.

use_memo lru_cache
Shared by One component instance Every caller, across instances, renders and apps
Keeps One value, for the latest deps Up to maxsize values, keyed by arguments
Freed When the component unmounts When evicted, or never with maxsize=None
Hits when deps equal last render's (==) The arguments equal a cached call's (hash, then ==)
Goes stale when compute reads a value missing from deps The function reads something besides its arguments
Defined Inside the component At module level

Prefer lru_cache when:

  • The computation reads only its arguments. Its key is its dependency list, so that list can't be incomplete.
  • Many components compute the same thing, such as rows formatting the same column widths. They all share one cache.
  • The inputs alternate, such as a sort order toggled back and forth. lru_cache keeps both results, while use_memo keeps one and recomputes on every toggle.

The file_list above, rewritten that way:

from functools import lru_cache


@lru_cache(maxsize=64)
def sorted_paths(paths: tuple[str, ...], descending: bool) -> tuple[str, ...]:
    return tuple(sorted(paths, reverse=descending))


@component
def file_list(paths: tuple[str, ...]) -> Div:
    use_focus(auto_focus=True)
    descending, set_descending = use_state(False)

    ordered = sorted_paths(paths, descending)
    ...

Prefer use_memo when:

  • The value captures the component's state or setters, as a handler does.
  • The inputs can't be hashed, such as lists, dicts and most mutable objects.
  • The value should go away with the component. A module-level cache keeps every argument and result it holds alive until they're evicted, and carries them between tests and between apps run in the same process.
  • The value is part of the component's output, such as an element whose children shouldn't re-run. That's meant for one instance, not for every instance that happens to pass equal arguments.
  • Each instance computes from its own input, such as a document per message in a transcript. A render with more instances than the cache's maxsize asks for more keys than it holds, in the same order every render, so each key is evicted before it's asked for again and nothing hits. use_memo keeps one value per instance, however many instances there are.

Don't put lru_cache on a function defined inside a component: every render defines a new function with an empty cache, so it never hits.

API

counterweight.hooks.use_memo

use_memo(
    compute: Getter[T], deps: tuple[object, ...]
) -> T
PARAMETER DESCRIPTION
compute

A zero-argument function that computes the value. It runs while the component renders: on the first render, and on every render whose deps changed.

TYPE: Getter[T]

deps

The values compute depends on. If any of them change (compared with ==), compute runs again. () computes the value once, when the component mounts. Unlike use_effect's, these can't be None: to compute on every render, don't use this hook.

TYPE: tuple[object, ...]

RETURNS DESCRIPTION
T

The value compute returned when deps last changed. It is the same object on every render until then, so an element returned from it keeps the components below it from re-running, and a handler returned from it can be passed to a memo component without making it re-run. The cached value MUST depend only on deps; check_purity on counterweight._app.app catches a value that goes stale.

counterweight.hooks.StaleMemo

Raised when check_purity is on and a use_memo whose deps didn't change computes something different from the value it cached, so the computation depends on something missing from its deps and the cached value is stale.