Skip to content

Dynamic Context

The dynamic context model is an enhanced version of the ReactPy use-context hook. In addition to providing application state that can be easily accessed by child components the dynamic context model allows the child components to change the state. Any changes made by a child component will update the context and will force the parent component and children to be re-rendered.

A typical usage would be where a deeply embedded child component, a drop-down element in a complex nested navigation component say, needs to update some element in the main application state.

 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
27
28
29
30
31
32
33
34
35
36
37
38
39
from reactpy import component, event, html, use_context, use_state

from reactpy_utils.types import EventArgs

from .app_context import AppContext, AppState


@component
def App():
    app_state, set_app_state = use_state(AppState())
    return AppContext(
        NavBar(),
        Content(),
        value=(app_state, set_app_state),
    )


@component
def Content():
    app_state, _ = use_context(AppContext)
    return html.div(
        html.h2(f"dark_mode={app_state.dark_mode}"),
    )


@component
def NavBar():
    return html.div(DarkModeButton())


@component
def DarkModeButton():
    app_state, set_app_state = use_context(AppContext)

    @event
    def on_click(_evt: EventArgs):
        set_app_state(app_state.update(dark_mode=not app_state.dark_mode))

    return html.button({"on_click": on_click}, "Toggle Dark Mode")
1
2
3
4
5
6
7
8
from reactpy_utils import DynamicContextModel, create_dynamic_context


class AppState(DynamicContextModel):
    dark_mode: bool = True


AppContext = create_dynamic_context(AppState)

Custom Context Models

By default context models are defined by sub-classing DynamicContextModel which itself is a subclass of the Pydantic, BaseModel. As an alternative you can also subclass the none-pydantic CustomDynamicContextModel or implement the protocol interface IDynamicContextModel

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
from reactpy_utils import CustomDynamicContextModel, create_dynamic_context

class CurrentUserState(CustomDynamicContextModel):

    def __init__(self, user_name: str, password:str, dark_mode: bool = True):
        super().__init__()
        self.user_name = user_name
        self.password = password
        self.dark_mode = dark_mode


AppContext = create_dynamic_context(CurrentUserState)

Last update: November 23, 2024
Authors: Steve Jones