Py.Cafe

maartenbreddels/

solara-custom-equals-in-use_state

State Change Demo with Custom Equals Function using Solara

DocsPricing
  • app.py
  • requirements.txt
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import solara


render_count = 0

@solara.component
def Page():
    global render_count
    render_count += 1

    # a custom equals function that only compares by object identity
    # uncomment the last part to see the normal/default behaviour
    some_list, set_some_list = solara.use_state([1, 2, 3], eq=lambda a, b: a is b)
    print("The component render function gets called")

    def set123():
        # even though the list may be the same, it will always re-render
        set_some_list([1, 2, 3])

    def set12():
        set_some_list([1, 2])

    solara.Button(label=f"Set to [1, 2, 3]", on_click=set123)
    solara.Button(label=f"Set to [1, 2]", on_click=set12)
    solara.Text(repr(some_list) + f" (rendered {render_count})")