Components often need to change what's on the screen as a result of an interaction. Typing into a form should update the input field, clicking "next" on an image carousel should change which image is displayed, clicking "buy" should put a product in the shopping cart. Components need to "remember" things: the current input value, the current image, the shopping cart. In ReactPy, this kind of component-specific memory is called state.
Here's a component that renders a sculpture image. Clicking "Next" should show the next sculpture by changing index to 1, then 2, and so on. However, this won't work (you can try it!):
1 2 3 4 5 6 7 8 910111213141516171819
@componentdefgallery():index=0defhandle_next(event):# `nonlocal` is what makes this assignment legal Python at all; without# it the nested function gets its own `index` and the read on the right# hand side raises UnboundLocalError. JS closures need no such keyword.nonlocalindexindex=index+1sculpture=sculptures[index]returnhtml.div(html.button({"onClick":handle_next},"Next"),html.h2(html.i(sculpture["name"])," by ",sculpture["artist"]),html.h3(f"({index+1} of {len(sculptures)})"),html.img({"src":sculpture["url"],"alt":sculpture["alt"]}),html.p(sculpture["description"]),)
sculptures=[{"name":"Homenaje a la Neurocirugía","artist":"Marta Colvin Andrade","description":"Although Colvin is predominantly known for abstract themes that allude to pre-Hispanic symbols, this gigantic sculpture, an homage to neurosurgery, is one of her most recognizable public art pieces.","url":"https://i.imgur.com/Mx7dA2Y.jpg","alt":"A bronze statue of two crossed hands delicately holding a human brain in their fingertips.",},{"name":"Floralis Genérica","artist":"Eduardo Catalano","description":"This enormous (75 ft. or 23m) silver flower is located in Buenos Aires. It is designed to move, closing its petals in the evening or when strong winds blow and opening them in the morning.","url":"https://i.imgur.com/ZF6s192m.jpg","alt":"A gigantic metallic flower sculpture with reflective mirror-like petals and strong stamens.",},{"name":"Eternal Presence","artist":"John Woodrow Wilson","description":'Wilson was known for his preoccupation with equality, social justice, as well as the essential and spiritual qualities of humankind. This massive (7ft. or 2,13m) bronze represents what he described as "a symbolic Black presence infused with a sense of universal humanity."',"url":"https://i.imgur.com/aTtVpES.jpg","alt":"The sculpture depicting a human head seems ever-present and solemn. It radiates calm and serenity.",},{"name":"Moai","artist":"Unknown Artist","description":"Located on the Easter Island, there are 1,000 moai, or extant monumental statues, created by the early Rapa Nui people, which some believe represented deified ancestors.","url":"https://i.imgur.com/RCwLEoQm.jpg","alt":"Three monumental stone busts with the heads that are disproportionately large with somber faces.",},{"name":"Blue Nana","artist":"Niki de Saint Phalle","description":"The Nanas are triumphant creatures, symbols of femininity and maternity. Initially, Saint Phalle used fabric and found objects for the Nanas, and later on introduced polyester to achieve a more vibrant effect.","url":"https://i.imgur.com/Sd1AgUOm.jpg","alt":"A large mosaic sculpture of a whimsical dancing female figure in a colorful costume emanating joy.",},{"name":"Ultimate Form","artist":"Barbara Hepworth","description":"This abstract bronze sculpture is a part of The Family of Man series located at Yorkshire Sculpture Park. Hepworth chose not to create literal representations of the world but developed abstract forms inspired by people and landscapes.","url":"https://i.imgur.com/2heNQDcm.jpg","alt":"A tall sculpture made of three elements stacked on each other reminding of a human figure.",},{"name":"Cavaliere","artist":"Lamidi Olonade Fakeye","description":"Descended from four generations of woodcarvers, Fakeye's work blended traditional and contemporary Yoruba themes.","url":"https://i.imgur.com/wIdGuZwm.png","alt":"An intricate wood sculpture of a warrior with a focused face on a horse adorned with patterns.",},{"name":"Big Bellies","artist":"Alina Szapocznikow","description":"Szapocznikow is known for her sculptures of the fragmented body as a metaphor for the fragility and impermanence of youth and beauty. This sculpture depicts two very realistic large bellies stacked on top of each other, each around five feet (1,5m) tall.","url":"https://i.imgur.com/AlHTAdDm.jpg","alt":"The sculpture reminds a cascade of folds, quite different from bellies in classical sculptures.",},{"name":"Terracotta Army","artist":"Unknown Artist","description":"The Terracotta Army is a collection of terracotta sculptures depicting the armies of Qin Shi Huang, the first Emperor of China. The army consisted of more than 8,000 soldiers, 130 chariots with 520 horses, and 150 cavalry horses.","url":"https://i.imgur.com/HMFmH6m.jpg","alt":"12 terracotta sculptures of solemn warriors, each with a unique facial expression and armor.",},{"name":"Lunar Landscape","artist":"Louise Nevelson","description":"Nevelson was known for scavenging objects from New York City debris, which she would later assemble into monumental constructions. In this one, she used disparate parts like a bedpost, juggling pin, and seat fragment, nailing and gluing them into boxes that reflect the influence of Cubism's geometric abstraction of space and form.","url":"https://i.imgur.com/rN7hY6om.jpg","alt":"A black matte sculpture where the individual elements are initially indistinguishable.",},{"name":"Aureole","artist":"Ranjani Shettar","description":'Shettar merges the traditional and the modern, the natural and the industrial. Her art focuses on the relationship between man and nature. Her work was described as compelling both abstractly and figuratively, gravity defying, and a "fine synthesis of unlikely materials."',"url":"https://i.imgur.com/okTpbHhm.jpg","alt":"A pale wire-like sculpture mounted on concrete wall and descending on the floor. It appears light.",},{"name":"Hippos","artist":"Taipei Zoo","description":"The Taipei Zoo commissioned a Hippo Square featuring submerged hippos at play.","url":"https://i.imgur.com/6o5Vuyu.jpg","alt":"A group of bronze hippo sculptures emerging from the sett sidewalk as if they were swimming.",},]
The handle_next event handler is updating a local variable, index. But two things prevent that change from being visible:
Local variables don't persist between renders. When ReactPy renders this component a second time, it renders it from scratch — it doesn't consider any changes to the local variables.
Changes to local variables won't trigger renders. ReactPy doesn't realize it needs to render the component again with the new data.
Both were checked against this exact component: clicking "Next" three times leaves the served VDOM byte-identical, and a later render caused by real state shows index back at 0 even though the handler had bumped it to 3.
To update a component with new data, two things need to happen:
Retain the data between renders.
Trigger ReactPy to render the component with new data (re-rendering).
use_state provides those two things:
A state variable to retain the data between renders.
A state setter function to update the variable and trigger ReactPy to render the component again.
To add a state variable, import use_state from reactpy at the top of the file:
fromreactpyimportcomponent,html,use_state
Then replace this line:
index=0
with
index,set_index=use_state(0)
index is a state variable and set_index is the setter function.
Python gives you the destructuring for free
React's const[index,setIndex]=useState(0) needs array destructuring syntax. In Python this is ordinary tuple unpacking, so there is nothing new to learn here — and unlike JavaScript, leaving out a name is a syntax error rather than a silent undefined.
This is how they work together in handle_next:
defhandle_next(event):set_index(index+1)
The handler needs nonlocal to read its own variable
If you keep the plain-variable version, the assignment inside the nested function is not legal Python without a declaration:
defhandle_next(event):nonlocalindexindex=index+1
Without it, Python treats index as a new local of handle_next, and reading it on the right-hand side raises UnboundLocalError. This is a Python scoping rule, not a ReactPy one — JavaScript closures just work. With use_state you never need it, because you read index and call set_index instead of assigning.
Now clicking the "Next" button switches the current sculpture:
1 2 3 4 5 6 7 8 9101112131415
@componentdefgallery():index,set_index=use_state(0)defhandle_next(event):set_index(index+1)sculpture=sculptures[index]returnhtml.div(html.button({"onClick":handle_next},"Next"),html.h2(html.i(sculpture["name"])," by ",sculpture["artist"]),html.h3(f"({index+1} of {len(sculptures)})"),html.img({"src":sculpture["url"],"alt":sculpture["alt"]}),html.p(sculpture["description"]),)
sculptures=[{"name":"Homenaje a la Neurocirugía","artist":"Marta Colvin Andrade","description":"Although Colvin is predominantly known for abstract themes that allude to pre-Hispanic symbols, this gigantic sculpture, an homage to neurosurgery, is one of her most recognizable public art pieces.","url":"https://i.imgur.com/Mx7dA2Y.jpg","alt":"A bronze statue of two crossed hands delicately holding a human brain in their fingertips.",},{"name":"Floralis Genérica","artist":"Eduardo Catalano","description":"This enormous (75 ft. or 23m) silver flower is located in Buenos Aires. It is designed to move, closing its petals in the evening or when strong winds blow and opening them in the morning.","url":"https://i.imgur.com/ZF6s192m.jpg","alt":"A gigantic metallic flower sculpture with reflective mirror-like petals and strong stamens.",},{"name":"Eternal Presence","artist":"John Woodrow Wilson","description":'Wilson was known for his preoccupation with equality, social justice, as well as the essential and spiritual qualities of humankind. This massive (7ft. or 2,13m) bronze represents what he described as "a symbolic Black presence infused with a sense of universal humanity."',"url":"https://i.imgur.com/aTtVpES.jpg","alt":"The sculpture depicting a human head seems ever-present and solemn. It radiates calm and serenity.",},{"name":"Moai","artist":"Unknown Artist","description":"Located on the Easter Island, there are 1,000 moai, or extant monumental statues, created by the early Rapa Nui people, which some believe represented deified ancestors.","url":"https://i.imgur.com/RCwLEoQm.jpg","alt":"Three monumental stone busts with the heads that are disproportionately large with somber faces.",},{"name":"Blue Nana","artist":"Niki de Saint Phalle","description":"The Nanas are triumphant creatures, symbols of femininity and maternity. Initially, Saint Phalle used fabric and found objects for the Nanas, and later on introduced polyester to achieve a more vibrant effect.","url":"https://i.imgur.com/Sd1AgUOm.jpg","alt":"A large mosaic sculpture of a whimsical dancing female figure in a colorful costume emanating joy.",},{"name":"Ultimate Form","artist":"Barbara Hepworth","description":"This abstract bronze sculpture is a part of The Family of Man series located at Yorkshire Sculpture Park. Hepworth chose not to create literal representations of the world but developed abstract forms inspired by people and landscapes.","url":"https://i.imgur.com/2heNQDcm.jpg","alt":"A tall sculpture made of three elements stacked on each other reminding of a human figure.",},{"name":"Cavaliere","artist":"Lamidi Olonade Fakeye","description":"Descended from four generations of woodcarvers, Fakeye's work blended traditional and contemporary Yoruba themes.","url":"https://i.imgur.com/wIdGuZwm.png","alt":"An intricate wood sculpture of a warrior with a focused face on a horse adorned with patterns.",},{"name":"Big Bellies","artist":"Alina Szapocznikow","description":"Szapocznikow is known for her sculptures of the fragmented body as a metaphor for the fragility and impermanence of youth and beauty. This sculpture depicts two very realistic large bellies stacked on top of each other, each around five feet (1,5m) tall.","url":"https://i.imgur.com/AlHTAdDm.jpg","alt":"The sculpture reminds a cascade of folds, quite different from bellies in classical sculptures.",},{"name":"Terracotta Army","artist":"Unknown Artist","description":"The Terracotta Army is a collection of terracotta sculptures depicting the armies of Qin Shi Huang, the first Emperor of China. The army consisted of more than 8,000 soldiers, 130 chariots with 520 horses, and 150 cavalry horses.","url":"https://i.imgur.com/HMFmH6m.jpg","alt":"12 terracotta sculptures of solemn warriors, each with a unique facial expression and armor.",},{"name":"Lunar Landscape","artist":"Louise Nevelson","description":"Nevelson was known for scavenging objects from New York City debris, which she would later assemble into monumental constructions. In this one, she used disparate parts like a bedpost, juggling pin, and seat fragment, nailing and gluing them into boxes that reflect the influence of Cubism's geometric abstraction of space and form.","url":"https://i.imgur.com/rN7hY6om.jpg","alt":"A black matte sculpture where the individual elements are initially indistinguishable.",},{"name":"Aureole","artist":"Ranjani Shettar","description":'Shettar merges the traditional and the modern, the natural and the industrial. Her art focuses on the relationship between man and nature. Her work was described as compelling both abstractly and figuratively, gravity defying, and a "fine synthesis of unlikely materials."',"url":"https://i.imgur.com/okTpbHhm.jpg","alt":"A pale wire-like sculpture mounted on concrete wall and descending on the floor. It appears light.",},{"name":"Hippos","artist":"Taipei Zoo","description":"The Taipei Zoo commissioned a Hippo Square featuring submerged hippos at play.","url":"https://i.imgur.com/6o5Vuyu.jpg","alt":"A group of bronze hippo sculptures emerging from the sett sidewalk as if they were swimming.",},]
In ReactPy, use_state, as well as any other function starting with use, is called a Hook.
Hooks are special functions that are only available while ReactPy is rendering (which we'll get into in more detail on the next page). They let you "hook into" different ReactPy features.
State is just one of those features, but you will meet the other Hooks later.
Call Hooks only at the top level
Hooks — functions starting with use — can only be called at the top level of your components or your own Hooks. You can't call Hooks inside conditions, loops, or other nested functions. Hooks are functions, but it's helpful to think of them as unconditional declarations about your component's needs. You "use" ReactPy features at the top of your component similar to how you "import" modules at the top of your file.
The check is not just advice: the reactpy-flake8 plugin (the ReactPy analogue of eslint-plugin-react-hooks, and part of this repo's own lint config) reports REACTPY102 for a Hook under a branch or in a loop:
@componentdefbad(flag):a,_=use_state("A")ifflag:# REACTPY102 hook 'use_state' used inside if statementb,_=use_state("B")returnhtml.p(b)returnhtml.p(a)
When you call use_state, you are telling ReactPy that you want this component to remember something:
index,set_index=use_state(0)
In this case, you want ReactPy to remember index.
The convention is to name this pair like something,set_something. You could name it anything you like, but conventions make things easier to understand across projects.
The only argument to use_state is the initial value of your state variable. In this example, the index's initial value is set to 0 with use_state(0).
Every time your component renders, use_state gives you a pair containing two values:
The state variable (index) with the value you stored.
The state setter function (set_index) which can update the state variable and trigger ReactPy to render the component again.
Here's how that happens in action:
index,set_index=use_state(0)
Your component renders the first time. Because you passed 0 to use_state as the initial value for index, it returns (0,set_index). ReactPy remembers 0 is the latest state value.
You update the state. When a user clicks the button, it calls set_index(index+1). index is 0, so it's set_index(1). This tells ReactPy to remember index is 1 now and triggers another render.
Your component's second render. ReactPy still sees use_state(0), but because ReactPy remembers that you set index to 1, it returns (1,set_index) instead.
And so on!
Pass a function for an expensive initial value
use_state accepts a callable and calls it only when the state is first created: use_state(lambda:json.loads(big_blob)). Passing the result of an expensive call instead — use_state(json.loads(big_blob)) — reparses on every render, because Python evaluates the argument before use_state ever runs.
You can have as many state variables of as many types as you like in one component. This component has two state variables, a number index and a boolean show_more that's toggled when you click "Show details":
1 2 3 4 5 6 7 8 910111213141516171819202122
@componentdefgallery():index,set_index=use_state(0)show_more,set_show_more=use_state(False)defhandle_next(event):set_index(index+1)defhandle_more(event):set_show_more(notshow_more)sculpture=sculptures[index]returnhtml.div(html.button({"onClick":handle_next},"Next"),html.h2(html.i(sculpture["name"])," by ",sculpture["artist"]),html.h3(f"({index+1} of {len(sculptures)})"),html.button({"onClick":handle_more},"Hide details"ifshow_moreelse"Show details"),html.p(sculpture["description"])ifshow_moreelseNone,html.img({"src":sculpture["url"],"alt":sculpture["alt"]}),)
sculptures=[{"name":"Homenaje a la Neurocirugía","artist":"Marta Colvin Andrade","description":"Although Colvin is predominantly known for abstract themes that allude to pre-Hispanic symbols, this gigantic sculpture, an homage to neurosurgery, is one of her most recognizable public art pieces.","url":"https://i.imgur.com/Mx7dA2Y.jpg","alt":"A bronze statue of two crossed hands delicately holding a human brain in their fingertips.",},{"name":"Floralis Genérica","artist":"Eduardo Catalano","description":"This enormous (75 ft. or 23m) silver flower is located in Buenos Aires. It is designed to move, closing its petals in the evening or when strong winds blow and opening them in the morning.","url":"https://i.imgur.com/ZF6s192m.jpg","alt":"A gigantic metallic flower sculpture with reflective mirror-like petals and strong stamens.",},{"name":"Eternal Presence","artist":"John Woodrow Wilson","description":'Wilson was known for his preoccupation with equality, social justice, as well as the essential and spiritual qualities of humankind. This massive (7ft. or 2,13m) bronze represents what he described as "a symbolic Black presence infused with a sense of universal humanity."',"url":"https://i.imgur.com/aTtVpES.jpg","alt":"The sculpture depicting a human head seems ever-present and solemn. It radiates calm and serenity.",},{"name":"Moai","artist":"Unknown Artist","description":"Located on the Easter Island, there are 1,000 moai, or extant monumental statues, created by the early Rapa Nui people, which some believe represented deified ancestors.","url":"https://i.imgur.com/RCwLEoQm.jpg","alt":"Three monumental stone busts with the heads that are disproportionately large with somber faces.",},{"name":"Blue Nana","artist":"Niki de Saint Phalle","description":"The Nanas are triumphant creatures, symbols of femininity and maternity. Initially, Saint Phalle used fabric and found objects for the Nanas, and later on introduced polyester to achieve a more vibrant effect.","url":"https://i.imgur.com/Sd1AgUOm.jpg","alt":"A large mosaic sculpture of a whimsical dancing female figure in a colorful costume emanating joy.",},{"name":"Ultimate Form","artist":"Barbara Hepworth","description":"This abstract bronze sculpture is a part of The Family of Man series located at Yorkshire Sculpture Park. Hepworth chose not to create literal representations of the world but developed abstract forms inspired by people and landscapes.","url":"https://i.imgur.com/2heNQDcm.jpg","alt":"A tall sculpture made of three elements stacked on each other reminding of a human figure.",},{"name":"Cavaliere","artist":"Lamidi Olonade Fakeye","description":"Descended from four generations of woodcarvers, Fakeye's work blended traditional and contemporary Yoruba themes.","url":"https://i.imgur.com/wIdGuZwm.png","alt":"An intricate wood sculpture of a warrior with a focused face on a horse adorned with patterns.",},{"name":"Big Bellies","artist":"Alina Szapocznikow","description":"Szapocznikow is known for her sculptures of the fragmented body as a metaphor for the fragility and impermanence of youth and beauty. This sculpture depicts two very realistic large bellies stacked on top of each other, each around five feet (1,5m) tall.","url":"https://i.imgur.com/AlHTAdDm.jpg","alt":"The sculpture reminds a cascade of folds, quite different from bellies in classical sculptures.",},{"name":"Terracotta Army","artist":"Unknown Artist","description":"The Terracotta Army is a collection of terracotta sculptures depicting the armies of Qin Shi Huang, the first Emperor of China. The army consisted of more than 8,000 soldiers, 130 chariots with 520 horses, and 150 cavalry horses.","url":"https://i.imgur.com/HMFmH6m.jpg","alt":"12 terracotta sculptures of solemn warriors, each with a unique facial expression and armor.",},{"name":"Lunar Landscape","artist":"Louise Nevelson","description":"Nevelson was known for scavenging objects from New York City debris, which she would later assemble into monumental constructions. In this one, she used disparate parts like a bedpost, juggling pin, and seat fragment, nailing and gluing them into boxes that reflect the influence of Cubism's geometric abstraction of space and form.","url":"https://i.imgur.com/rN7hY6om.jpg","alt":"A black matte sculpture where the individual elements are initially indistinguishable.",},{"name":"Aureole","artist":"Ranjani Shettar","description":'Shettar merges the traditional and the modern, the natural and the industrial. Her art focuses on the relationship between man and nature. Her work was described as compelling both abstractly and figuratively, gravity defying, and a "fine synthesis of unlikely materials."',"url":"https://i.imgur.com/okTpbHhm.jpg","alt":"A pale wire-like sculpture mounted on concrete wall and descending on the floor. It appears light.",},{"name":"Hippos","artist":"Taipei Zoo","description":"The Taipei Zoo commissioned a Hippo Square featuring submerged hippos at play.","url":"https://i.imgur.com/6o5Vuyu.jpg","alt":"A group of bronze hippo sculptures emerging from the sett sidewalk as if they were swimming.",},]
It is a good idea to have multiple state variables if their state is unrelated, like index and show_more in this example. But if you find that you often change two state variables together, it might be easier to combine them into one. For example, if you have a form with many fields, it's more convenient to have a single state variable that holds a dict than a state variable per field. Read Choosing the State Structure for more tips.
State is local to a particular invocation of a component — like a local variable. Render the same component twice and each copy gets its own state.
1 2 3 4 5 6 7 8 910111213141516171819
@componentdefgallery():index,set_index=use_state(0)sculpture=sculptures[index]returnhtml.section(html.button({"onClick":lambdaevent:set_index(index+1)},"Next",),html.h3(f"({index+1} of {len(sculptures)})"),html.img({"src":sculpture["url"],"alt":sculpture["alt"]}),)@componentdefpage():# Two separate mounts of the same component. Each call site is a different# position in the tree, so each gallery keeps its own index.returnhtml.div(gallery(),gallery())
sculptures=[{"name":"Homenaje a la Neurocirugía","artist":"Marta Colvin Andrade","description":"Although Colvin is predominantly known for abstract themes that allude to pre-Hispanic symbols, this gigantic sculpture, an homage to neurosurgery, is one of her most recognizable public art pieces.","url":"https://i.imgur.com/Mx7dA2Y.jpg","alt":"A bronze statue of two crossed hands delicately holding a human brain in their fingertips.",},{"name":"Floralis Genérica","artist":"Eduardo Catalano","description":"This enormous (75 ft. or 23m) silver flower is located in Buenos Aires. It is designed to move, closing its petals in the evening or when strong winds blow and opening them in the morning.","url":"https://i.imgur.com/ZF6s192m.jpg","alt":"A gigantic metallic flower sculpture with reflective mirror-like petals and strong stamens.",},{"name":"Eternal Presence","artist":"John Woodrow Wilson","description":'Wilson was known for his preoccupation with equality, social justice, as well as the essential and spiritual qualities of humankind. This massive (7ft. or 2,13m) bronze represents what he described as "a symbolic Black presence infused with a sense of universal humanity."',"url":"https://i.imgur.com/aTtVpES.jpg","alt":"The sculpture depicting a human head seems ever-present and solemn. It radiates calm and serenity.",},{"name":"Moai","artist":"Unknown Artist","description":"Located on the Easter Island, there are 1,000 moai, or extant monumental statues, created by the early Rapa Nui people, which some believe represented deified ancestors.","url":"https://i.imgur.com/RCwLEoQm.jpg","alt":"Three monumental stone busts with the heads that are disproportionately large with somber faces.",},{"name":"Blue Nana","artist":"Niki de Saint Phalle","description":"The Nanas are triumphant creatures, symbols of femininity and maternity. Initially, Saint Phalle used fabric and found objects for the Nanas, and later on introduced polyester to achieve a more vibrant effect.","url":"https://i.imgur.com/Sd1AgUOm.jpg","alt":"A large mosaic sculpture of a whimsical dancing female figure in a colorful costume emanating joy.",},{"name":"Ultimate Form","artist":"Barbara Hepworth","description":"This abstract bronze sculpture is a part of The Family of Man series located at Yorkshire Sculpture Park. Hepworth chose not to create literal representations of the world but developed abstract forms inspired by people and landscapes.","url":"https://i.imgur.com/2heNQDcm.jpg","alt":"A tall sculpture made of three elements stacked on each other reminding of a human figure.",},{"name":"Cavaliere","artist":"Lamidi Olonade Fakeye","description":"Descended from four generations of woodcarvers, Fakeye's work blended traditional and contemporary Yoruba themes.","url":"https://i.imgur.com/wIdGuZwm.png","alt":"An intricate wood sculpture of a warrior with a focused face on a horse adorned with patterns.",},{"name":"Big Bellies","artist":"Alina Szapocznikow","description":"Szapocznikow is known for her sculptures of the fragmented body as a metaphor for the fragility and impermanence of youth and beauty. This sculpture depicts two very realistic large bellies stacked on top of each other, each around five feet (1,5m) tall.","url":"https://i.imgur.com/AlHTAdDm.jpg","alt":"The sculpture reminds a cascade of folds, quite different from bellies in classical sculptures.",},{"name":"Terracotta Army","artist":"Unknown Artist","description":"The Terracotta Army is a collection of terracotta sculptures depicting the armies of Qin Shi Huang, the first Emperor of China. The army consisted of more than 8,000 soldiers, 130 chariots with 520 horses, and 150 cavalry horses.","url":"https://i.imgur.com/HMFmH6m.jpg","alt":"12 terracotta sculptures of solemn warriors, each with a unique facial expression and armor.",},{"name":"Lunar Landscape","artist":"Louise Nevelson","description":"Nevelson was known for scavenging objects from New York City debris, which she would later assemble into monumental constructions. In this one, she used disparate parts like a bedpost, juggling pin, and seat fragment, nailing and gluing them into boxes that reflect the influence of Cubism's geometric abstraction of space and form.","url":"https://i.imgur.com/rN7hY6om.jpg","alt":"A black matte sculpture where the individual elements are initially indistinguishable.",},{"name":"Aureole","artist":"Ranjani Shettar","description":'Shettar merges the traditional and the modern, the natural and the industrial. Her art focuses on the relationship between man and nature. Her work was described as compelling both abstractly and figuratively, gravity defying, and a "fine synthesis of unlikely materials."',"url":"https://i.imgur.com/okTpbHhm.jpg","alt":"A pale wire-like sculpture mounted on concrete wall and descending on the floor. It appears light.",},{"name":"Hippos","artist":"Taipei Zoo","description":"The Taipei Zoo commissioned a Hippo Square featuring submerged hippos at play.","url":"https://i.imgur.com/6o5Vuyu.jpg","alt":"A group of bronze hippo sculptures emerging from the sett sidewalk as if they were swimming.",},]
Click "Next" in one gallery and the other doesn't budge. Each call to gallery() is a separate component instance with its own state.
This is the same mechanism behind Passing Props to a Component: the person prop is local to one invocation of Profile(), so two Profile() calls don't share it. State works the same way.
Because state belongs to the instance and not the function, two galleries can drift apart — which is sometimes what you want, and sometimes not. Sharing State Between Components covers the case where they must move together.
How does ReactPy know which state to return?
You might have noticed that the use_state call does not receive any information about which state variable it refers to. There is no "identifier" passed to use_state, so how does it know which state to return? Does it rely on some magic like parsing your functions? The answer is no.
Instead, to enable their concise syntax, Hooks rely on a stable call order on every render of the same component. ReactPy appends each Hook's state to a list on the component's first render, then walks that list by position on every render after (LifeCycleHook.use_state in core/_life_cycle_hook.py). This works well in practice because if you follow the rule above ("only call Hooks at the top level"), Hooks are always called in the same order — and reactpy-flake8 catches most mistakes.
What happens when the order does change is worth knowing, because one of the two outcomes fails silently:
A Hook appears where there was none before → IndexError:listindexoutofrange, the render aborts, and the error is logged.
A Hook stops being called → the Hooks after it shift up one slot and quietly receive the wrong values. Nothing is logged, and the component keeps rendering.
Measured with two use_state calls that vanish behind a branch, the surviving Hook got the first slot's value while its own was left orphaned. That is far harder to debug than a crash, which is exactly why the top-level rule is enforced rather than merely recommended.