Skip to content

Sharing State Between Components

Overview

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 ReactPy code.

You will learn

  • How to share state between two components
  • How to coordinate components by lifting state to their common parent
  • What controlled and uncontrolled components are

Lifting state up by example

In this example, a parent accordion() component renders two separate panel()s:

  • accordion()
    • panel()
    • panel()

Each panel() component has a boolean is_active state that determines whether its content is visible.

Press the Show button for both panels:

 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
@component
def panel(title, *children):
    is_active, set_is_active = use_state(False)

    return html.section(
        {"className": "panel"},
        html.h3(title),
        html.p(*children)
        if is_active
        else html.button({"onClick": lambda event: set_is_active(True)}, "Show"),
    )


@component
def accordion():
    return html(
        html.h2("Almaty, Kazakhstan"),
        panel(
            "About",
            "With a population of about 2 million, Almaty is Kazakhstan's "
            "largest city. From 1929 to 1997, it was its capital city.",
        ),
        panel(
            "Etymology",
            "The name comes from алма, the Kazakh word for “apple” and is "
            "often translated as “full of apples”.",
        ),
    )
1
2
3
4
5
6
7
8
9
h3,
p {
    margin: 5px 0;
}

.panel {
    padding: 10px;
    border: 1px solid #aaa;
}
1
# TODO

Notice how pressing one panel's button does not affect the other panel — they are independent.

But now let's say you want to change it so that only one panel is expanded at any given time. With that design, expanding the second panel should collapse the first one. How would you do that?

To coordinate these two panels, you need to "lift their state up" to a parent component in three steps:

  1. Remove state from the child components.
  2. Pass hardcoded data from the common parent.
  3. Add state to the common parent and pass it down together with the event handlers.

This will allow the accordion() component to coordinate both panel()s and only expand one at a time.

Step 1: Remove state from the child components

You will give control of the panel()'s is_active to its parent component. This means that the parent component will pass is_active to panel() as a prop instead. Start by removing this line from the panel() component:

is_active, set_is_active = use_state(False)

And instead, add is_active to the panel()'s list of props:

@component
def panel(title, is_active, *children):

Now the panel()'s parent component can control is_active by passing it down as a prop. Conversely, the panel() component now has no control over the value of is_active — it's now up to the parent component!

Step 2: Pass hardcoded data from the common parent

To lift state up, you must locate the closest common parent component of both of the child components that you want to coordinate:

  • accordion() (closest common parent)
    • panel()
    • panel()

In this example, it's the accordion() component. Since it's above both panels and can control their props, it will become the "source of truth" for which panel is currently active. Make the accordion() component pass a hardcoded value of is_active (for example, True) to both panels:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
@component
def panel(title, is_active, *children):
    return html.section(
        {"className": "panel"},
        html.h3(title),
        html.p(*children) if is_active else html.button("Show"),
    )


@component
def accordion():
    return html(
        html.h2("Almaty, Kazakhstan"),
        panel("About", True, "With a population of about 2 million..."),
        panel("Etymology", True, "The name comes from алма..."),
    )
1
2
3
4
5
6
7
8
9
h3,
p {
    margin: 5px 0;
}

.panel {
    padding: 10px;
    border: 1px solid #aaa;
}
1
# TODO

Try editing the hardcoded is_active values in the accordion() component and see the result on the screen.

Step 3: Add state to the common parent

Lifting state up often changes the nature of what you're storing as state.

In this case, only one panel should be active at a time. This means that the accordion() common parent component needs to keep track of which panel is the active one. Instead of a bool value, it could use a number as the index of the active panel() for the state variable:

active_index, set_active_index = use_state(0)

When the active_index is 0, the first panel is active, and when it's 1, it's the second one.

Clicking the "Show" button in either panel() needs to change the active index in accordion(). A panel() can't set the active_index state directly because it's defined inside the accordion(). The accordion() component needs to explicitly allow the panel() component to change its state by passing an event handler down as a prop:

panel(
    "About",
    active_index == 0,
    lambda event: set_active_index(0),
    ...
)

The html.button() inside the panel() will now use the on_show prop as its click event handler:

 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
@component
def panel(title, is_active, on_show, *children):
    return html.section(
        {"className": "panel"},
        html.h3(title),
        (html.p(*children) if is_active else html.button({"onClick": on_show}, "Show")),
    )


@component
def accordion():
    active_index, set_active_index = use_state(0)

    return html(
        html.h2("Almaty, Kazakhstan"),
        panel(
            "About",
            active_index == 0,
            lambda event: set_active_index(0),
            "With a population of about 2 million, Almaty is Kazakhstan's "
            "largest city. From 1929 to 1997, it was its capital city.",
        ),
        panel(
            "Etymology",
            active_index == 1,
            lambda event: set_active_index(1),
            "The name comes from алма, the Kazakh word for “apple” and is "
            "often translated as “full of apples”.",
        ),
    )
1
2
3
4
5
6
7
8
9
h3,
p {
    margin: 5px 0;
}

.panel {
    padding: 10px;
    border: 1px solid #aaa;
}
1
# TODO

This completes lifting state up! Moving state into the common parent component allowed you to coordinate the two panels. Using the active index instead of two "is shown" flags ensured that only one panel is active at a given time. And passing down the event handler to the child allowed the child to change the parent's state.

Controlled and uncontrolled components

It is common to call a component with some local state "uncontrolled". For example, the original panel() component with an is_active state variable is uncontrolled because its parent cannot influence whether the panel is active or not.

In contrast, you might say a component is "controlled" when the important information in it is driven by props rather than its own local state. This lets the parent component fully specify its behavior. The final panel() component with the is_active prop is controlled by the accordion() component.

Uncontrolled components are easier to use within their parents because they require less configuration. But they're less flexible when you want to coordinate them together. Controlled components are maximally flexible, but they require the parent components to fully configure them with props.

In practice, "controlled" and "uncontrolled" aren't strict technical terms — each component usually has some mix of both local state and props. However, this is a useful way to talk about how components are designed and what capabilities they offer.

When writing a component, consider which information in it should be controlled (via props), and which information should be uncontrolled (via state). But you can always change your mind and refactor later.

A single source of truth for each state

In a ReactPy application, many components will have their own state. Some state may "live" close to the leaf components (components at the bottom of the tree) like inputs. Other state may "live" closer to the top of the app. For example, a router implemented in ReactPy would keep the current route in the state of a component near the root, and pass it down by props.

For each unique piece of state, you will choose the component that "owns" it. This principle is also known as having a "single source of truth". It doesn't mean that all state lives in one place — but that for each piece of state, there is a specific component that holds that piece of information. Instead of duplicating shared state between components, lift it up to their common shared parent, and pass it down to the children that need it.

Your app will change as you work on it. It is common that you will move state down or back up while you're still figuring out where each piece of the state "lives". This is all part of the process!

To see what this feels like in practice with a few more components, read Thinking in React.

Summary

  • When you want to coordinate two components, move their state to their common parent.
  • Then pass the information down through props from their common parent.
  • Finally, pass the event handlers down so that the children can change the parent's state.
  • It's useful to consider components as "controlled" (driven by props) or "uncontrolled" (driven by state).
Authors: Archmonger