Hooks
Rules of hooks
Section titled “Rules of hooks”Call hooks at the top level of a Kitex component’s render function, in the same order on every render, before any conditional return. Kitex associates each hook with its position in that component, not its variable name. Don’t call hooks inside an if, a loop, an event handler, or an effect callback. Instead, call the hook during render and use the value or function it returns later. For a list, give each row its own component and call its hooks there.
State: replace a value or update the current one
Section titled “State: replace a value or update the current one”UseState(initial) returns a getter (func() T) and a setter (kitex.StateSetter[T]). Read with query(), not query. The setter is callable and assignable directly to a func(T) callback; no wrapper is needed for an input:
var filter = kitex.FC("Filter", func(kitex.NoProps) kitex.Node { query, setQuery := kitex.UseState("") return kitex.Fragment( kitex.Input(kitex.InputProps{Value: query(), OnValueChange: setQuery}), kitex.Button(kitex.ButtonProps{OnPress: func() { setQuery("") }}, kitex.Text("Clear")), )})Use set(next) when you know the replacement. When the next value depends on the previous one, use set.Update: it reads, transforms, and writes under one lock, so concurrent goroutines don’t lose increments. A separate set(count() + 1) is not atomic. Keep the transformation short and don’t call the same slot’s getter or setter from inside it.
var clock = kitex.FC("Clock", func(kitex.NoProps) kitex.Node { seconds, setSeconds := kitex.UseState(0) kitex.UseInterval(func() { setSeconds.Update(func(n int) int { return n + 1 }) }, time.Second) return kitex.Textf("Elapsed: %ds", seconds())})var Counter = kitex.FC("Counter", func(kitex.NoProps) kitex.Node { count, setCount := kitex.UseState(0)
return kitex.Box.Style( demo.Default.Column(), kitex.Textf("Count: %d", count()), kitex.Box.Style( demo.Default.ButtonRow, ActionButton("Increment", func() { setCount.Update(func(n int) int { return n + 1 }) }), ActionButton("Reset", func() { setCount(0) }), ), )})Lazy initial state
Section titled “Lazy initial state”Go evaluates UseState(loadInitialItems()) on every render, even though Kitex only uses the first value. Pass the function itself to UseStateFunc for expensive synchronous initialization. A non-nil initializer runs once per mount. Passing a nil initializer panics on any render, even after the state has been initialized. The getter and StateSetter are identical to UseState’s. For blocking I/O, use an async effect instead.
func loadInitialItems() []string { return strings.Fields("build test release") }
var queue = kitex.FC("Queue", func(kitex.NoProps) kitex.Node { items, setItems := kitex.UseStateFunc(loadInitialItems) return kitex.Button(kitex.ButtonProps{OnPress: func() { setItems(nil) }}, kitex.Textf("Clear queue (%d)", len(items())), )})Group transitions with a reducer
Section titled “Group transitions with a reducer”UseReducer(reducer, initial) returns a state getter and dispatch(action). Use it when a transition has rules worth testing independently of the UI:
type Page struct{ Number int }type Move int
func turnPage(p Page, by Move) Page { return Page{Number: max(1, p.Number + int(by))}}
var pager = kitex.FC("Pager", func(kitex.NoProps) kitex.Node { page, dispatch := kitex.UseReducer(turnPage, Page{Number: 1}) return kitex.Fragment( kitex.Button(kitex.ButtonProps{OnPress: func() { dispatch(-1) }}, kitex.Text("Previous")), kitex.Textf("Page %d", page().Number), kitex.Button(kitex.ButtonProps{OnPress: func() { dispatch(1) }}, kitex.Text("Next")), )})Memoized values, callbacks, and refs
Section titled “Memoized values, callbacks, and refs”UseMemo(factory, deps...) caches the factory’s result. UseCallback(fn, deps...) caches the function itself. Both compare dependencies in order, element by element, using == for comparable types (including pointers by identity) and structural comparison (still comparing pointers by identity) otherwise; with no dependencies the first result lasts for the mount. Pass the values used by the computation, not a getter function. Non-nil Go functions never compare equal as dependencies, so a function used as a dependency causes a cache miss even if it is a stable callback.
type NamesProps struct{ Names []string }
var namesView = kitex.FC("Names", func(p NamesProps) kitex.Node { sorted := kitex.UseMemo(func() []string { names := slices.Clone(p.Names) slices.Sort(names) return names }, p.Names) return kitex.Text(strings.Join(sorted, ", "))})Publish a new slice when data changes: mutating the old backing array also changes what the previous dependency points to. Use UseCallback when passing a handler to a memoized child or context consumer (below). Use UseRef(initial) when you want a persistent mutable Current value, without scheduling a render. See attaching a typed input ref.
Effects and async work
Section titled “Effects and async work”Unlike React, omitting deps means once on mount, not after every render. Supply dependencies to repeat work when their values change. Choose an EveryRender variant only when the work really must follow each render. Cleanup runs before the next setup and on unmount.
| Hook | When setup runs | Teardown |
|---|---|---|
UseEffect / UseEffectCleanup |
After commit, on mount and changed dependencies | Only the Cleanup form returns a cleanup from setup |
UseEffectEveryRender / UseEffectEveryRenderCleanup |
After each committed render | Same cleanup rule; no dependency arguments |
UseLayoutEffect / UseLayoutEffectCleanup |
Synchronously after reconciliation, on mount and changed dependencies | Same cleanup rule; keep synchronous work short |
UseLayoutEffectEveryRender / UseLayoutEffectEveryRenderCleanup |
Synchronously after reconciliation on each render | Same cleanup rule; no dependency arguments |
UseAsyncEffect |
Starts background work after commit, on mount and changed dependencies | Kitex cancels its context.Context before restarting, on unmount, or when the scheduler stops |
Return the subscription’s cancel function, not the result of calling it. This component counts document keydowns for as long as it is mounted:
var keyCount = kitex.FC("KeyCount", func(kitex.NoProps) kitex.Node { document := kitex.UseDocument() count, setCount := kitex.UseState(0) kitex.UseEffectCleanup(func() func() { doc := document() if doc == nil { return nil } sub := doc.AddEventListener(event.EventKeyDown, func(event.Event) { setCount.Update(func(n int) int { return n + 1 }) }) return sub.Cancel }) return kitex.Textf("Keydowns: %d", count())})Cancellation is cooperative. Here switching feeds cancels the old wait even if its channel never closes. For a network call, pass the supplied context into the request too.
type FeedProps struct{ Messages <-chan string }
var ticker = kitex.FC("Feed", func(p FeedProps) kitex.Node { latest, setLatest := kitex.UseState("Waiting…") kitex.UseAsyncEffect(func(ctx context.Context) { for { select { case <-ctx.Done(): return case msg, ok := <-p.Messages: if !ok || ctx.Err() != nil { return } setLatest(msg) } } }, p.Messages) return kitex.Text(latest())})Share values with context
Section titled “Share values with context”Create the context once. UseContext reads and subscribes to the nearest provider of that context. Without one, it returns the default passed to CreateContext:
var theme = kitex.CreateContext("light")var themeLabel = kitex.FC("ThemeLabel", func(kitex.NoProps) kitex.Node { return kitex.Text(kitex.UseContext(theme))})var darkPanel = kitex.FC("DarkPanel", func(kitex.NoProps) kitex.Node { return theme.Provider("dark", themeLabel())})Context values need not be comparable. This provider shares both recent searches and an action. The action captures a stable setter, not a particular render’s slice; Update supplies the current slice at call time.
type History struct { Recent []string Add func(string)}
var history = kitex.CreateContext(History{})
var historyPanel = kitex.FCC("HistoryPanel", func(_ kitex.NoProps, children ...kitex.Node) kitex.Node { recent, setRecent := kitex.UseState([]string(nil)) add := kitex.UseCallback(func(term string) { setRecent.Update(func(prev []string) []string { return append(slices.Clone(prev), term) }) }) return history.Provider(History{Recent: recent(), Add: add}, children...)})
var historySummary = kitex.FC("HistorySummary", func(kitex.NoProps) kitex.Node { h := kitex.UseContext(history) return kitex.Textf("Recent searches: %d", len(h.Recent))})type themeState struct { Dark bool Toggle func()}
var themeContext = kitex.CreateContext(themeState{})
var ThemeChoice = kitex.FC("ThemeChoice", func(kitex.NoProps) kitex.Node { t := kitex.UseContext(themeContext) name := "Light" if t.Dark { name = "Dark" }
return kitex.Box.Style( demo.Default.Column(), kitex.Text("Theme: "+name), ActionButton("Change theme", t.Toggle), )})
var ContextDemo = kitex.FC("ContextDemo", func(kitex.NoProps) kitex.Node { dark, setDark := kitex.UseState(false) toggle := kitex.UseCallback(func() { setDark.Update(func(old bool) bool { return !old }) })
return themeContext.Provider( themeState{Dark: dark(), Toggle: toggle}, ThemeChoice(), )})Mount historyPanel(historySummary()) to connect them. A changed provider value notifies subscribers. Safely comparable types use ==. For other values Kitex compares fields, recognizing shared pointer and map identities and same-length slices sharing a starting address; different identities can still compare equal by content. Publish new data instead of mutating an already-provided pointer, slice, or map. UseCallback keeps actions equal across unrelated renders. For custom value equality, implement EquatableProps; don’t ignore actions whose behavior can change.
Export func fields and fields that implement EquatableProps on context structs so Kitex can compare callback identity or call Equal, respectively. Kitex conservatively treats unexported func fields as unequal.
Keyboard shortcuts and timers
Section titled “Keyboard shortcuts and timers”Use UseKey for a single document keydown combo. For example, an editor can pass its save and quit actions as props:
type EditorProps struct { Save func(string) Quit func()}
var Editor = kitex.FC("Editor", func(p EditorProps) kitex.Node { draft, setDraft := kitex.UseState("") kitex.UseKey("ctrl+s", func() { p.Save(draft()) }, p.Save) kitex.UseKey("q", p.Quit, p.Quit)
return kitex.Box.Style( demo.Default.ButtonRow, kitex.Input(kitex.InputProps{ Value: draft(), Placeholder: "Type here...", OnValueChange: setDraft, Style: demo.Default.Input.Width(style.Cells(22)), }), kitex.Button(kitex.ButtonProps{ Style: demo.Default.PrimaryButton, OnPress: func() { p.Save(draft()) }, }, kitex.Text("Save")), )})
var UseKeyDemo = kitex.FC("UseKeyDemo", func(kitex.NoProps) kitex.Node { status, setStatus := kitex.UseState("Ready") layout := demo.Default.Container. Display(style.DisplayFlex). FlexDirection(style.FlexColumn). Gap(1, 0)
return kitex.Box.Style( layout, Editor.Props(EditorProps{ Save: func(text string) { setStatus("Saved: " + text) }, Quit: func() { setStatus("Quit") }, }), kitex.Box.Style(demo.Default.MutedText, kitex.Text(status())), )})Supply a non-nil Save in this example. Typing q into the focused input edits the text: the control prevents the default, so the document shortcut skips it. An unhandled ctrl+s still fires. UseKey replaces its listener when the combo, handler nilness, or dependencies change and removes it on unmount. Disable it with "" or a nil handler rather than conditionally calling the hook.
Without dependencies, an enabled shortcut keeps its original handler while the combo stays the same. Include captured values that can change; a state getter such as draft() reads the current value when invoked, so edits don’t need to be dependencies. The function props above deliberately cause re-subscription on render because of Go’s deep-equality rule for functions.
Use UseKeyboard(handler func(event.KeyEvent), deps ...any) to inspect the full keydown or handle several keys in one listener. Unlike UseKey, it doesn’t filter prevented events for you; check e.DefaultPrevented() if controls should get first refusal.
UseTimeout(handler, delay, deps...) queues a one-shot callback; UseInterval(handler, interval, deps...) queues repeated callbacks (use a positive interval). Both stop the timer on unmount and replace it when the duration or dependencies change. The clock above uses an interval; for a debounced preview, restart a timeout on each text change:
var preview = kitex.FC("Preview", func(kitex.NoProps) kitex.Node { draft, setDraft := kitex.UseState("") shown, setShown := kitex.UseState("") text := draft() kitex.UseTimeout(func() { setShown(text) }, 200*time.Millisecond, text) return kitex.Fragment( kitex.Input(kitex.InputProps{Value: text, OnValueChange: setDraft}), kitex.Text(shown()), )})DOM, focus, and terminal reference
Section titled “DOM, focus, and terminal reference”Call the hook during render. For hooks that return a getter, resolve the handle when needed and check for nil, especially before mount or after unmount.
Signature (in kitex) |
Use |
|---|---|
UseFocus(ref Ref[dom.Element]) bool |
Track focus and blur of the referenced element. Use UseRef[dom.Element](nil) for this signature. |
UseWindowFocus() bool |
Track focus of the terminal window, not of an individual control. |
UseViewportSize() geom.Size |
Read viewport dimensions in cells; updates on resize. |
UseColorScheme() style.ColorScheme |
Read the host’s preferred scheme and follow changes; it can be unknown. |
UseElement() func() dom.Node |
Get the component’s first real DOM node, if any. For a particular descendant, attach a ref. |
UseDocument() func() dom.Document |
Resolve the owning document, for example to subscribe in an effect. |
UseTerminal() func() terminal.Terminal |
Resolve the document’s terminal to access host services. |
UseTitle(initialTitle string) (func() string, func(string)) |
Read and set the title; Kitex applies changes to the terminal window. |
UseBell() func() |
Get a bell callback during render; invoke it in a handler, not during render. |
UseProgressBar() func(state terminal.ProgressBarState, percentage int) |
Update the host’s native progress indicator. |
UseProgramResume() func(resume *terminal.ProgramResume) |
Register a resume command on a supporting terminal; pass nil to clear it. |