Skip to main content

Async State Management

Design walkthrough for Dim’s bottom-up useStore: nested useState leaves, window CustomEvents, and cross-component sync. For the shipped API (5-tuples, encryption), see Encrypted Storage and the API overview.

State management in UI frameworks is typically top-down. Dim explores a bottom-up approach: any component that uses the same store shape can subscribe and set shared state via custom events.

The target API looks like this (today each leaf is a 5-tuple — see note at the end):

const {
form: {
input: [inputValue, setInputValue, isLoading, , isSaving],
},
todos: [todos, setTodos, todosLoading, , todosSaving],
} = useStore({
form: {
input: useState(""),
},
todos: useState([]),
});

The input is a schema for the state; the return value keeps the same object shape. If any component uses this store with this shape, it can subscribe to and set changes.

Custom events make that work: when a setter runs, it dispatches a CustomEvent. Other components listening for that key update their local state.


Creating the useStore hook​

A naive first step is an identity function over the nested useState tuples — enough to sketch the shape before wiring persistence and events:

export const useStore = (store) => {
return store;
};

The real hook (next sections) registers listeners, persists to IndexedDB, and enhances each leaf. Do not ship this stub.


Creating the AsyncronousStateManager​

We inspect the shape of the store object to create identifiers for the properties we want to listen to. We can then create a custom event listener for each property. we would need some kind of storage manager to handle the state and the listeners.


class AsyncronousStateManager {
private store: any = {};
private eventListener: any[] = [];

generateListener(listener) {
const { listenerId, key, value } = listener;

// Remove existing event listeners if they exist
const existingListender = this.eventListener.find(
(listener) => listener.listenerId === listenerId
);

const listenerName = `${key}`;

if (existingListender) {
window.removeEventListener(listenerName, existingListender.listener);

this.eventListener = this.eventListener.filter(
(listener) => listener.listenerId !== listenerId
);
}

// Create a new event listener
const newListener = (event) => {
value[1](event.detail);

this.store = {
...this.store,
[key]: event.detail,
};
};

window.addEventListener(listenerName, newListener);

this.eventListener.push({
listenerId,
listener: newListener,
});

const newSetter = (newValue) => {
window.dispatchEvent(
new CustomEvent(listenerName, {
detail: newValue,
})
);
};

const newState = this.store[key] || value[0];

return [newState, newSetter];
}

removeListeners(listenerId) {
const existingListender = this.eventListener.find(
(listener) => listener.listenerId === listenerId
);

if (existingListender) {
window.removeEventListener(
`${existingListender.key}`,
existingListender.listener
);

this.eventListener = this.eventListener.filter(
(listener) => listener.listenerId !== listenerId
);
}
}
}

const asyncronousStateManager = new AsyncronousStateManager();

Lets break this down.

  • The AsyncronousStateManager class is a class that has a store property that is an object that holds the state. The eventListener property is an array that holds the event listeners.
  • The generateListener method is a method that generates a new event listener. The method takes a listener object as an argument. The listener object has a listenerId, key, and value properties. The listenerId property is a unique identifier for the listener. The key property is the key of the state in the store object. The value property is an array with the value and setter from the useState hook.
  • The generateListener method first removes existing event listeners if they exist, then creates a new event listener. this is so it always uses the latest state. The new event listener updates the state in the store object and calls the setter from the useState hook.
  • The removeListeners method is a method that removes event listeners. The method takes a listenerId as an argument then removes the event listener with the given listenerId from the eventListener array.

Creating the createListeners function​

Now that we have a way to create and remove event listeners, we can now use it to event listeners that trigger state updates. lets create a function to traverse the store object and create event listeners for each property.

const createListeners = (store, listenerId) => {
const traverse = (obj, path) => {
Object.keys(obj).forEach((key) => {
if (typeof obj[key] === "object" && obj[key].length === undefined) {
traverse(obj[key], `${path}${key}.`);
} else {
const [asyncState, asyncSetState] =
asyncronousStateManager.generateListener({
listenerId,
key: `${path}${key}`,
value: obj[key],
});

obj[key] = [asyncState, asyncSetState].concat(obj[key]);
}
});
};

traverse(store, "");
};

The createListeners function is a function that creates event listeners for each property in the store object. The function takes the store object and a listenerId as arguments. The function uses a traverse function to traverse the store object and create event listeners for each property.


Putting it all together​

Now lets update our useStore hook to put it all together

export const useStore = (store) => {
const [randomId] = useState(crypto.getRandomValues(new Uint8Array(8)));

createListeners(store, randomId);

useEffect(() => {
return () => {
asyncronousStateManager.removeListeners(randomId);
};
}, []);

return store;
};

Note: The shipped useStore enhances each leaf to a 5-tuple [value, setter, isLoading, setIsLoading, isSaving] and supports optional encrypted persistence. See Bottom-up Browser Storage and Encrypted Storage & Loading States.


Conclusion​

I dont recomend using this approach to create any production ready applications. This is more of an experiment to see if we can create asynchrounous state management for web components. Im sure there are more changes that can be made to make it better. I would like to hear your thoughts on this approach and if you think it could be improved in any way.