State
A reactive value that automatically triggers UI redraw when changed.
Basic Usage
counter := NewState(0)
counter.Bind(window)
// In your UI
Text(fmt.Sprintf("Count: %d", counter.Get()))
// Update the value (triggers redraw)
counter.Set(counter.Get() + 1)
Creating State
// Create state with initial value
counter := NewState(0)
name := NewState("John")
isEnabled := NewState(true)
Methods
| Method | Description | Example |
|---|---|---|
NewState[T](initial) |
Creates a new reactive state | NewState(0) |
Get() |
Returns the current value | counter.Get() |
Set(value) |
Sets a new value and triggers redraw | counter.Set(5) |
Update(fn) |
Applies a function to update the value | counter.Update(func(n int) int { return n + 1 }) |
Bind(window) |
Binds state to a window for reactivity | counter.Bind(w) |
Type Constraint
State works with any comparable type:
// Integers
count := NewState(0)
// Strings
name := NewState("")
// Booleans
visible := NewState(true)
// Custom types (must be comparable)
type Status int
status := NewState(Status(0))
Examples
// Counter example
func run(w *app.Window) error {
counter := NewState(0).Bind(w)
// ... in render loop
Column([]any{
Text(fmt.Sprintf("Count: %d", counter.Get())),
Button("Increment", OnClick(func() {
counter.Set(counter.Get() + 1)
})),
Button("Decrement", OnClick(func() {
counter.Update(func(n int) int { return n - 1 })
})),
})
}
// Toggle example
func run(w *app.Window) error {
isDark := NewState(false).Bind(w)
// ... in render loop
theme := Light
if isDark.Get() {
theme = Dark
}
Button("Toggle Theme", OnClick(func() {
isDark.Set(!isDark.Get())
}))
}
// Text input example
func run(w *app.Window) error {
name := NewState("").Bind(w)
Column([]any{
TextField(
Hint("Enter name"),
OnChange(func(s string) {
name.Set(s)
}),
),
Text(fmt.Sprintf("Hello, %s!", name.Get())),
})
}
Thread Safety
State is thread-safe. You can safely call Get(), Set(), and Update() from any goroutine.