Store Pages in a Variable / dcc.store in order to have a faster multi page app

Hi,

As I mentioned to you in private, it is possible to store the page in dcc.Store directly because Dash converts automatically the components into json objects.

Here is a trivial example of a multi-page application where the page updates are made clientside:

from dash import Dash, html, dcc, Input, Output, State, callback, clientside_callback

app = Dash(__name__)

pages_dict = {
    "/": html.Div(
        [
            html.H1("Home!"),
            dcc.Link("Go to Page 1", href="/page1"),
            html.Br(),
            dcc.Link("Go to Page 2", href="/page2"),
        ]
    ),
    "/page1": html.H1("Page 1"),
    "/page2": html.H1("Page 2"),
}

app.layout = html.Div(
    [
        html.Div(id="content"),
        dcc.Store(id="store", data=pages_dict),
        dcc.Location(id="url"),
    ]
)

clientside_callback(
    """
    (pathname, pages) => pages[pathname]
    """,
    Output("content", "children"),
    Input("url", "pathname"),
    State("store", "data"),
)

if __name__ == "__main__":
    app.run_server(debug=True)

For further reference, note also that a component can be written as a dictionary (or JS object clientside) in the following way:

{
    "namespace": "dash_html_components",
    "type": "Div",
    "props": {
        "id": "example",
        "children": [
            {
                "namespace": "dash_html_components",
                "type": "H1",
                "children": "Hello world!"
            }
        ]
    }
}
1 Like