@k8ordo/state

How it works

When and where @k8ordo/state reads and writes state, and what it does and does not guarantee.

On this page

Definitions and stores

text
shared   definePageState / defineLocalState / defineSessionState
         defineCookieState / defineMemoryState
           ↓ import                     ↓ import
server   parseUrl(searchParams)       client   useAppState(def)
         parseCookies(cookies)                 → [state, update]
         href(path, values)

A definition is plain data: schemas and pure functions, or initial values in place of schemas for memory state. Loading the module touches neither navigation, localStorage nor document.cookie, so a definition imports as is on the server and in tests.

The store is created in the browser by the first useAppState call and registered under the place’s kind and the definition’s string key. An HMR re-evaluation of the definition module reconnects to the same store as long as the key is the same.

No store is created on the server. In the server render and the hydration render, useAppState returns the defaults, or a memory state’s initial values. Only the fields handed in through initialUrl or initialCookie take the values passed. The browser’s values take over after hydration.

No Provider

The URL, the history entry, Web Storage and the cookie jar each exist once in the browser. The stores read and write them directly, so there is nothing for a Provider to scope.

The flip side is that a store outlives each test. Clearing it with resetStateRegistry() after every test is covered in “Testing”.

Router requirements

Only an update() that changes the URL depends on the router: it needs one that calls intercept() on the navigate event. Links, GET forms and an update() that leaves the URL alone need nothing.

An update() that changes the URL calls navigation.navigate(). Under @k8ordo/router, which includes every page rendered by @k8ordo/framework, a navigation that keeps the pathname is treated as a state change. Nothing remounts, and scroll and focus stay where they are. update() has already rendered the new values, so finished settles once that navigation does.

Only a page that exports search under @k8ordo/framework’s server mode loads again when the query moves, and finished waits until it is on screen (see “Parameters”).

Values the schema rejects

A value read back from the URL, the history entry, Web Storage or a cookie is treated as input. It is read in these steps.

  1. Parse with the whole schema. If that passes, it is done.
  2. If not, read each field with its own schema, and keep the ones that pass.
  3. Run what was kept through the whole schema again. An object-level .refine() runs here.
  4. If that still fails, everything falls back to the defaults, which the definition already checked against the whole schema.

The second whole parse is handed the fields as they were read, not their outputs, because a field such as z.stringbool() cannot take its own output as input.

A url value written by update() is turned into a query string and read again, the same way a visitor’s URL is read (see “URL”). entry, Web Storage and cookies hand the written values to the schema as they are, without a string in between. There the schema must accept its own output.

Change detection

The keys to compare come from the definition: the schema’s keys, or a memory state’s initial values. Whether something changed is decided key by key.

Arrays and plain objects are compared by content, everything else with Object.is. A Date, a Map or a class instance compares by reference, so a new Date for the same moment still counts as a change.

Shared places

The URL and the history entry are shared with other definitions, the router and tracking parameters. A page state rewrites only its own parameters, and only its own namespace in the entry state. Every other value is carried over with each write.

What is written is built from the browser’s values at that moment with the batch on top. Building it from the rendered values would erase what another tab or another definition wrote in between. When another write lands while a batch is still pending, the batch stays on top of it.

Cookie writes are asynchronous, so they run one at a time. The next write reads the cookie only after the previous one has landed. Two batches never overwrite each other’s fields with stale values.

Guarantees

  • Reading a value back from its place never throws, even when the schema rejects it. A rejected value falls back to its default.
  • In every place with a schema, the values update() hands the next render have passed it.
  • An update() that changes both url and entry writes them to one history entry in a single navigation.navigate(). Back and forward bring both back together.
  • A write lays only the fields its batch changed over the browser’s current values. Everything else keeps what another tab or another definition wrote in the meantime.
  • A field that did not change keeps its previous reference. A subscription to some keys re-renders only when one of those keys changed.
  • The server render and the hydration render always show the same values.
  • Under @k8ordo/router and @k8ordo/framework, a page state reads the URL of the page it renders in. While the next page loads, the page still on screen keeps the values it was left with, and the next page renders with its own URL’s from its first render.
  • An update() called from the page being left while the next page loads writes nothing, and its finished settles at once.

Not guaranteed

  • Two definitions of the same kind under one key raise no error and no warning. They share one store.
  • The server render never reflects localStorage, sessionStorage or entry values. The server cannot read those places.
  • Under a router that does not call intercept() on the navigate event, an update() that changes the URL is a full document load. There is no History API fallback. Next.js is one today; see “Next.js”.
  • A value mutated in place is not detected as a change. Mutating a nested object re-renders nothing.
  • Memory state values are not validated. With no schema, whatever update() receives goes in as it is.
  • A write to Web Storage or a cookie can be refused, by a full quota or a cookie over 4 KB. The rendered value stays, and the update() handle rejects.
  • A browser that blocks site data fails with a SecurityError on any read of localStorage or sessionStorage. defineLocalState and defineSessionState state render their defaults. A value set with update() stays in memory until the next load, and the handle rejects with that error.
  • Under a router that does not say which page a component renders in, a page state follows the URL. A host of your own built on @k8ordo/router’s useInterceptedNavigation is one.
k8ordo

React libraries that use Baseline features without holding back.