edifice.provide_context#

edifice.provide_context(context_key, initial_state)[source]#

Context shared state provider.

Provides similar features to React useContext.

Parameters:
  • context_key (str) – Identifier for a shared context.

  • initial_state (Union[TypeVar(_T_provide_context), Callable[[], TypeVar(_T_provide_context)]]) – The initial state value or initializer function.

Return type:

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

Returns:

A tuple pair containing

  1. The current state value for the given context_key.

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

Use this Hook to transmit state without passing the state down through the props to a child @component using use_context() or use_context_select().

provide_context() is called with a context_key and an initial value. It returns a state value and a setter function. The initial value, state value and setter function behave exactly like the ones documented in use_state().

The context_key must be unique for each provide_context() Hook.

The setter function will, when called, update the state value across each @component using use_context() with the same context_key.

Example provide_context, use_context#
@component
def ContextChild(self):
    x, x_setter = use_context("x_context_key", int)

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

@component
def ContextParent(self):
    x, _x_setter = provide_context("x_context_key", 0)

    with VBoxview():
        Label(text=str(x))
        ContextChild()
        ContextChild()

Editorial Comments#

Prop drilling is when you pass a prop down through many levels of components to get the prop to a child component. This sounds arduous but most of the time prop drilling is what you should do. Prop drilling makes your program easier to understand and maintain because it makes the dependencies between components explicit.

provide_context() and use_context() should be used rarely or never.