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
The current state value for the given
context_key.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
@componentusinguse_context()oruse_context_select().provide_context()is called with acontext_keyand 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 inuse_state().The
context_keymust be unique for eachprovide_context()Hook.The setter function will, when called, update the state value across each
@componentusinguse_context()with the samecontext_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()anduse_context()should be used rarely or never.