Concurrency and the browser
Keep component state on the UI goroutine, and reach JavaScript, storage and notifications from Go.
This page covers how an app runs in the browser: the one goroutine that owns the UI and how to work around it, the
Value
type that reaches JavaScript, local and session storage, notifications, environment variables and logging. Every API here compiles on the server too, where most of it does nothing.
States and actions, which also cross goroutines, are on State and actions . Testing code that uses these APIs is on Testing .
§1 The UI goroutine
An app has one UI goroutine, an event loop. Rendering, lifecycle hooks, event handlers, component action handlers, state deliveries to observers, and the functions given to
Dispatch
and
Defer
all run on it, one at a time. Read and write component fields only there. Code on any other goroutine hands its results over with
Dispatch
.
One thing at a time
Blocking work
func
(
ctx
Context
)
Dispatch
(
fn
func
(
Context
)
)
func
(
ctx
Context
)
Defer
(
fn
func
(
Context
)
)
func
(
ctx
Context
)
Update
(
)
func
(
ctx
Context
)
PreventUpdate
(
)
-
Dispatchqueuesfnon the UI goroutine and flags the component thatctxbelongs to, and each of its ancestors, for a re-render. It can be called from any goroutine. If the component is no longer mounted whenfn's turn comes,fnis skipped. - Re-renders are batched. Flagged components are updated on the next frame, and in the browser frames run at most 120 times a second, only while there is work.
-
Deferqueuesfnto run after the next frame's updates, when the page shows them. It flags nothing for update, and it is skipped if the component is no longer mounted.ctx.ScrollTouses it. -
UpdateisDispatch(nil): it only flags the component and its ancestors. -
PreventUpdatewithdraws one pending flag from the component and each of its ancestors. An event handler flags its component once, so callingPreventUpdatein the handler skips that re-render.
Event handlers run through
Dispatch
, which is why a click handler can set a field and the component re-renders without any other call.