State Management Recipes
The four things Web Components are usually challenged on — state management, data fetching, style isolation and performance — all have concrete answers here; the answers are just scattered across component pages and specs. This page pins down state management: the library does not ship an application-level store; a host store plus oas-* events is the standard answer. The four scenarios below show how that boundary works in practice.
Scenario 1: Controlled / uncontrolled inside a component
At component level there are only two modes, and picking the wrong one is more common than picking the wrong library:
- Uncontrolled: pass no controlled attribute; read the user's action from the event
detail(oas-change/oas-sort-change/oas-filter-change, etc.). - Controlled: the host passes attributes (
value/checked/sort-key/sort-order/filter-values, etc.); after interaction the component writes the latest value back to the same attribute. Reading the attribute gives the current value; the event is only a notification. When the two disagree, the attribute written by the host wins.
Naming and write-back timing follow one convention: controlled attributes and event detail payloads map one-to-one, the event is not "the only source of truth", and the component's internal state is just a projection of the attribute. The full contract lives in the controlled / uncontrolled chapter of ui-spec; concrete examples are on Input, Combobox and Table's controlled sorting.
Rule of thumb: the host needs to read back or override the value → controlled; the host only needs to know what the user did → uncontrolled. Do not mix the two (half attribute, half event write-back), or you will get "the user clicked but the host state did not change".
Scenario 2: URL-driven state (table sorting / filtering and the query string)
The most common list-page requirement is "keep the filter after refresh, make the link shareable, and preserve state across back/forward". There is one way to do it: the URL is the single source of truth, and the table's controlled attributes are its projection. Three directions:
- Read the URL on init: turn
sort/order/filtersintosort-key/sort-order/filter-values. - Write the URL on change: listen to
oas-sort-change/oas-filter-changeand copy the component's already-written controlled attributes into the query (history.replaceState, no history entry). - Refill on back / forward: on
popstate, re-parse the URL and write the attributes back; do not write the URL again here, or you create a loop.
const table = document.querySelector('oas-table')!
// 1) URL -> controlled attributes
const applyUrl = (): void => {
const params = new URLSearchParams(location.search)
const sort = params.get('sort')
const order = params.get('order')
if (sort && (order === 'asc' || order === 'desc')) {
table.setAttribute('sort-key', sort)
table.setAttribute('sort-order', order)
} else {
table.removeAttribute('sort-key')
table.removeAttribute('sort-order')
}
const filters = params.get('filters')
if (filters) table.setAttribute('filter-values', filters)
else table.removeAttribute('filter-values')
}
// 2) Controlled attributes -> URL (events are only the trigger; read the attribute for consistency)
const writeUrl = (): void => {
const params = new URLSearchParams(location.search)
const sort = table.getAttribute('sort-key')
const order = table.getAttribute('sort-order')
if (sort && order) {
params.set('sort', sort)
params.set('order', order)
} else {
params.delete('sort')
params.delete('order')
}
const filters = table.getAttribute('filter-values')
if (filters) params.set('filters', filters)
else params.delete('filters')
history.replaceState(null, '', `${location.pathname}?${params}`)
}
table.addEventListener('oas-sort-change', writeUrl)
table.addEventListener('oas-filter-change', writeUrl)
// 3) Back / forward: URL -> controlled attributes (refill only, never write the URL)
window.addEventListener('popstate', applyUrl)
applyUrl()Notes and pitfalls:
- Writing the attribute is the request: under
row-model="server"/infinite, changing the sort / filter attributes drivesoas-rows-request(reason=sort/filter); the host does not need to call the fetcher again. - Multi-column sorting:
multi-sortis a JSON array attribute; serialize it into the query the same way; whenmulti-sortand single-columnsort-key/sort-orderare both present,multi-sortwins. - Filter values are a JSON object string: the
filter-valuesformat is exactly{"city":"Shanghai"}; letURLSearchParamsencode it. The component writes an empty string when filters are cleared — treat that as "no filter". - Do not listen to your own URL writes:
replaceStatedoes not firepopstate, so there is no loop; only user back / forward refills.
Scenario 3: Storage sync (localStorage)
When the user opens the same list again, they expect the previous sort and filters. Use a table instance plugin to persist the "view state" in localStorage. This reuses the sample plugin in the table plugin section: view-state persistence instead of repeating the implementation:
// The full implementation (~40 lines) is on the linked page; copy it as-is
import { createViewStatePersistence } from './table-plugins'
table.plugins = [createViewStatePersistence('my-app:orders:view')]The sample plugin's contract (identical to the official plugin mechanism):
- Only fills what the host did not set: if the template already has
sort-key, the template wins; stored values never override explicit initial values. - Storage failures degrade silently: private mode / quota exceeded / corrupted JSON all fall back to "not persisted" without affecting the table.
- Instance state stays in the closure: a plugin object may be shared by several tables; a factory produces a fresh object per instance, so state never leaks across instances.
- Automatic cleanup:
api.onCleanupunsubscribes when the plugin is removed or the table disconnects, leaving no dangling listeners.
If you need cross-tab sync, add a storage listener on the host side (the plugin only writes on this page; a write in another tab is not announced here except via storage):
window.addEventListener('storage', (event) => {
if (event.key !== 'my-app:orders:view' || !event.newValue) return
const saved = JSON.parse(event.newValue) as Record<string, string>
if (saved.sortKey) table.setAttribute('sort-key', saved.sortKey)
if (saved.sortOrder) table.setAttribute('sort-order', saved.sortOrder)
if (saved.multiSort) table.setAttribute('multi-sort', saved.multiSort)
if (saved.filterValues) table.setAttribute('filter-values', saved.filterValues)
})Storage sync boundary: the component never reads or writes storage (
localStorage/sessionStorage/ IndexedDB are all host choices). The plugin only composes the official host API into a reusable shape; switching backends means changing the sample plugin'sread/savefunctions.
Scenario 4: Cross-component aggregation (form submit)
When several controls form one business form, the standard pattern is the form as the write channel and the host store as the single source of truth, not controls listening to each other. Pick one of two shapes:
Native form aggregation (one-shot submit): oas-form collects and validates fields with a name and emits oas-submit; detail.values is a nested structure (dot paths such as profile.city and users.0.name are assembled back into objects). Note that oas-form wraps a native <form> inside its shadow root, so a light-DOM button has no native submit semantics — call the public method from the button click:
form.addEventListener('oas-submit', async (event) => {
const values = event.detail.values
await api.save(values)
})
// A light-DOM oas-button click: delegates to the inner form's requestSubmit; validation and events unchanged
submitButton.addEventListener('oas-click', () => form.submit())On validation failure the form emits oas-validate-fail and no oas-submit; field-level messages are rendered by the form core. For field-level reactions / live aggregation, switch to the controlled shape.
schema-form controlled values (live aggregation): oas-schema-form's values property is the field value source; each host change is written by leaf-path diff (no DOM rebuild, no focus loss). Only user interaction emits oas-values-change; host writes do not echo, so you can store the event result and write it back directly:
let store = { name: '', tags: [] as string[] }
schema.values = store // initial / external data change: host writes do not echo, no loop
schema.addEventListener('oas-values-change', (event) => {
store = event.detail.values
})
schema.addEventListener('oas-submit', (event) => {
store = event.detail.values
api.save(store)
})Aggregation boundary: components do not talk to each other directly. Cross-component collaboration such as "selected table rows → form initial values" or "form submit → table refresh" always goes through the host store / business functions; components only emit
oas-*events. When you need to inject configuration nearby (theme, locale, size), use theoas-config-providerprovider pattern — that is configuration, not business state.
Closing the four pain points: style isolation and performance
The answer to state management is "the host owns state, components project it". The other two pain points are already handled by mechanisms; briefly:
- Style isolation: Shadow DOM keeps component styles and page styles from polluting each other; theming runs on CSS variable tokens (including dark / high-contrast variants), and customization has three openings: CSS variables →
::part()→ slots. See Theming and Design Tokens. - Performance: not a verbal promise — on-demand entries plus per-chain size budgets and CI
perf:size/perf:browsergates prevent regressions release over release; for large datasets use the windowed data protocol (see Data Fetching Recipes).
Related
- Where data comes from: Data Fetching Recipes · Server-side windowed data
- Table capabilities: Table · Plugin mechanism · Cell context menu
- Form capabilities: Form · Schema Form
- Events and integration: Event conventions in Getting Started · Framework integration