Managing State#

What You’ll Learn
How to Structure State

Make it easy to reason about your application with strategies for organizing state.

Sharing Component State

Allow components to vary vary together, by lifting state into common parents.

When and How to Reset State

Control if and how state is preserved by understanding it’s relationship to the “UI tree”.

Simplifying Updates with Reducers

Consolidate state update logic outside your component in a single function, called a “reducer”.

Deeply Sharing State with Contexts

Instead of passing shared state down deep component trees, bring state into “contexts” instead.

Combining Contexts and Reducers

You can combine reducers and context together to manage state of a complex screen.

Section 1: How to Structure State#

Note

Under construction 🚧

Section 2: Shared Component State#

Sometimes, you want the state of two components to always change together. To do it, remove state from both of them, move it to their closest common parent, and then pass it down to them via props. This is known as “lifting state up”, and it’s one of the most common things you will do writing code with ReactPy.

In the example below the search input and the list of elements below share the same state, the state represents the food name. Note how the component Table gets called at each change of state. The component is observing the state and reacting to state changes automatically, just like it would do in React.

from reactpy import component, hooks, html, run


@component
def SyncedInputs():
    value, set_value = hooks.use_state("")
    return html.p(
        Input("First input", value, set_value),
        Input("Second input", value, set_value),
    )


@component
def Input(label, value, set_value):
    def handle_change(event):
        set_value(event["target"]["value"])

    return html.label(
        label + " ", html.input({"value": value, "on_change": handle_change})
    )


run(SyncedInputs)

Read More

Allow components to vary vary together, by lifting state into common parents.

Section 3: When and How to Reset State#

Note

Under construction 🚧

Section 4: Simplifying Updates with Reducers#

Note

Under construction 🚧

Section 5: Deeply Sharing State with Contexts#

Note

Under construction 🚧

Section 6: Combining Contexts and Reducers#

Note

Under construction 🚧