Appearance
State
State is data that belongs to one instance of a component. Barton creates it when the component first appears, keeps it across renders, and renders the component again whenever an event handler changes it.
Declaring state
Nest a type named State and take it in render.
cpp
struct Toggle {
struct State {
bool on = false;
};
View render(const State& state) const {
return Text { state.on ? "On" : "Off" };
}
};Rendering only reads state. Changes happen in event handlers.
Initial state
To seed state from the component's props, give State a constructor that takes the component. Barton calls it once, when the state is created.
cpp
struct Counter {
struct State {
explicit State(const Counter& counter) : clicks { counter.start } {}
int clicks;
};
View render(const State& state) const {
return Text { std::format("Clicks: {}", state.clicks) };
}
int start = 0;
};
Counter { 12 } // starts at 12Without that constructor, Barton default-constructs State, so member initializers like bool on = false; are enough.
The constructor only runs on creation. If the parent later passes a different start, the existing state keeps its value. When a value should always follow a prop, read the prop in render instead of copying it into state.
Lifetime
State belongs to a component at a particular place in the tree. It's created when a component of that type first appears there, and destroyed once the component is no longer rendered. If the component appears again later, it starts with fresh state.
Changing state
Event handlers take State&. When a handler returns, Barton renders the component again.
cpp
Container {
on_click = [](State& state) { state.on = !state.on; },
Text { state.on ? "On" : "Off" },
}Handlers declare only what they use. An event, the state, the window list and app data can come in any combination. See Parameters for the full list.
cpp
on_select = [](const SelectEvent& select, State& state) {
state.fruit = select.index;
},Props or state?
If the parent decides it, it's a prop. If the component decides it, it's state.