liveBook · Manning

Shared mutable state

As explained in Web Component Development with Modern Libraries and Tooling

The coordination of one data state across multiple components so their representations remain synchronized.

A shopping cart may have one web component showing its items and another showing the item count and total price. When the cart changes, both displays need to stay synchronized. Mutable shared state gives multiple components access to the same changing data. section 3.11

Vanilla web components have no built-in state-sharing mechanism. One approach keeps state in an ancestor, passes it down through component properties, and listens for bubbling events from descendants that request changes. It works, but passing data through components that do not use it can be tedious and error prone. section 3.11 section 3.12

One name, three components

A FAST state object starts with a name of "World". A labeled input reads that name and replaces the state when its change event fires; a greeting reads the same name and updates automatically. A parent component can also reset the state to "World". The input, greeting, and reset action therefore coordinate without passing the name through the component hierarchy. section 7.11

import { state } from "@microsoft/fast-element/state.js";

export const myState = state({ name: "World" });

The short state definition creates the shared object used by the components. section 7.11

With FAST, components read `myState.current.name` and make changes through `myState.set(...)`. The input example creates a replacement object that preserves other current properties while changing `name`. Related shared properties can be grouped in one state object, or separated into multiple objects. Choose an explicit ancestor-and-events flow for vanilla components, or a library’s state support when that plumbing becomes cumbersome. section 7.11 section 3.11

How Web Component Development with Modern Libraries and Tooling covers it

How deep it goes
Works through an ancestor-and-events approach and a FAST state-object example, without detailing the state function’s internals.
Examples
Uses a shopping-cart item list and totals, plus a shared name edited by an input and restored by a reset button.
What it assumes
Assumes familiarity with web components, properties, and events while showing how to define and use a FAST state object.
What you can do after
Apply it via FAST’s `state` function to synchronize components, or implement ancestor-held state with properties and bubbling events.
How it connects
Connects web components to component properties, bubbling events, reactive updates, and state objects.

Also explained in

Compare how 8 books explain shared mutable state →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Web Component Development with Modern Libraries and Tooling. The section links point to the parts of the book it draws on.