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.
fromreactpyimportcomponent,event,html,use_context,use_statefromreactpy_utils.typesimportEventArgsfrom.app_contextimportAppContext,AppState@componentdefApp():app_state,set_app_state=use_state(AppState())returnAppContext(NavBar(),Content(),value=(app_state,set_app_state),)@componentdefContent():app_state,_=use_context(AppContext)returnhtml.div(html.h2(f"dark_mode={app_state.dark_mode}"),)@componentdefNavBar():returnhtml.div(DarkModeButton())@componentdefDarkModeButton():app_state,set_app_state=use_context(AppContext)@eventdefon_click(_evt:EventArgs):set_app_state(app_state.update(dark_mode=notapp_state.dark_mode))returnhtml.button({"on_click":on_click},"Toggle Dark Mode")
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