Skip to content

Pure components (memoizable components) #1011

@mofojed

Description

@mofojed

As a developer I would like to be able to memoize each component, such that it does not re-render in the render cycle if none of the props have changed.

There should be two ways to do this:

  1. Use a ui.use_memo to wrap returning an element, such that the element is not re-rendered if the props have not changed. E.g. something like this should work, and not call the slow_component whenever a new colour is selected:
from deephaven import ui
import time


@ui.component
def my_slow_form(on_submit):
    print("SLOW COMPONENT RENDER...")
    time.sleep(1)
    return ui.form(
        ui.text_field(label="Name", name="name"),
        on_submit=on_submit
    )


@ui.component
def my_app():
    bg, set_bg = ui.use_state('red')

    handle_click = ui.use_callback(lambda e: print(f"Form submitted: {e}"), [])

    # memoize rendering the slow form with a `use_memo`
    slow_form = ui.use_memo(lambda: my_slow_form(handle_click), [handle_click])

    return ui.view(
        ui.picker("salmon", "lemonchiffon", "green", "red", selected_key=bg, on_change=set_bg),
        slow_form,
        background_color=bg,
        padding="size-100"
    )

app = my_app()

However, in that above example it is re-rendering the slow form each time the colour is changed. That's because the ui.use_memo wraps creating the renderable element, but the element isn't actually rendered until a render cycle (from the user) anyway.
2. Add a is_pure (or memoize?) flag to the @ui.component wrapper (defaulting to false), e.g.

from deephaven import ui


@ui.component(is_pure=True)
def my_pure_component(param1: str, param2: str):
    ...

Indicating it is a pure component should ensure that it does not re-render the component unless one of the provided props has changed.

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions