edifice.use_state

edifice.use_state#

class edifice.use_state(initial_state)[source]#

Bases:

Persistent mutable state Hook inside a edifice.component() function.

Behaves like React useState.

When use_state() is called, it returns a state value and a setter function.

The state value will be the value of the state at the beginning of the render for this component.

The setter function will, when called, set the state value before the next render. If the new state value is not __eq__ to the old state value, then the component will be re-rendered.

Example:

@component
def Stateful(self):
    x, x_setter = use_state(0)

    Button(
        title=str(x)
        on_click = lambda _event: x_setter(x + 1)
    )

If an updater function is passed to the setter function, then at the end of the render the state will be modified by calling all of the updater functions in this order in which they were passed. An updater function is a function from the previous state to the new state.

Example:

@component
def Stateful(self):
    x, x_setter = use_state(0)

    def updater(x_previous):
        return x_previous + 1

    Button(
        title=str(x)
        on_click = lambda _event: x_setter(updater)
    )

If any of the updater functions raises an exception, then all state updates will be cancelled and the state value will be unchanged for the next render.

Do not mutate the state variable. The old state variable must be left unmodified so that it can be compared to the new state variable during the next render. If your state variable is a collection, then create a shallow copy of it to pass to the setter function:

def Stateful(self):
    x, x_setter = use_state(cast(list[str], []))

    def updater(x_previous):
        x_new = x_previous[:]
        x_new.append("Label Text " + str(len(x_previous)))
        return x_new

    with View():
        Button(
            title="Add One",
            on_click = lambda _event: x_setter(updater)
        )
        for t in x:
            Label(text=t)

A good technique for declaring immutable state datastructures is to use frozen dataclasses. Use the replace() function to update the dataclass. To shallow-copy a list, slice the entire list like list_new = list_old[:].

Warning

You can’t store a callable value in use_state, because it will be mistaken for an updater function. If you want to store a callable value, like a function, then wrap it in a tuple or some other non-callable data structure.

Parameters:

initial_state (TypeVar(_T_use_state)) – The initial state value.

Return type:

tuple[TypeVar(_T_use_state), Callable[[Union[TypeVar(_T_use_state), Callable[[TypeVar(_T_use_state)], TypeVar(_T_use_state)]]], None]]

Returns:

A tuple pair containing

  1. The current state value.

  2. A setter function for setting or updating the state value.