Skip to content
Writing
Engineering
· · 3 min

A state manager in under a kilobyte

listen to this article from the Wonder Why? podcast
Listen

In 2020, I built two state management libraries for React. Overstateful, at approximately 590 bytes gzipped, and Broadstate, at 388 bytes.

They addressed similar problems through fundamentally different APIs.

Overstateful was inspired by Redux. Broadstate was inspired by something considerably simpler: useState.

Looking back, I'm less interested in how small I managed to make these libraries and more interested in understanding exactly how much machinery shared state actually requires.

Removing the prerequisite

Overstateful retained the familiar relationship between actions, reducers and a central store.

const store = createStore(
  { count: 0 },
  [countReducer]
);

// Inside a component
const [state, dispatch] = useOverState();
dispatch(addOne());

The infrastructure was considerably smaller than the ecosystem that inspired it, but the programming model remained.

Broadstate approached the problem differently.

export const counter = createObservable(0);

// Inside any consuming component
const [count, setCount] = useBroadState(counter);

If you understood useState, you already understood much of the API.

There was no requirement to understand action types or reducers before incrementing a number. State ownership moved outside the component, while its consumption remained familiar.

The interesting thing is how little code that distinction actually requires.

Reconstructing Broadstate

At its simplest, an observable needs three things: a value, a collection of subscribers and a mechanism for notifying them when that value changes.

Here's how I'd reconstruct the underlying idea today.

type Update<T> = T | ((previous: T) => T);

function createObservable<T>(initial: T) {
  let value = initial;
  const listeners = new Set<() => void>();

  return {
    getSnapshot: () => value,

    subscribe(listener: () => void) {
      listeners.add(listener);
      return () => {
        listeners.delete(listener);
      };
    },

    set(update: Update<T>) {
      const next =
        typeof update === "function"
          ? (update as (prev: T) => T)(value)
          : update;

      if (Object.is(value, next)) return;

      value = next;
      [...listeners].forEach(listener => listener());
    },
  };
}

Nothing here depends on React. The observable owns the value; React is simply one of its consumers.

counter = createObservable(2)
value
2
listeners · 3
CartButtonStepperSummary
<CartButton />
2Basket
<Stepper />
Oat milk2
<Summary />
2 items£5.80
Press + on the stepper, then set the same value again. Only a real change reaches the listeners.

React 18 introduced , which makes the integration considerably more interesting than it was in 2020.

import { useSyncExternalStore } from "react";

function useBroadState<T>(
  observable: ReturnType<typeof createObservable<T>>
) {
  const value = useSyncExternalStore(
    observable.subscribe,
    observable.getSnapshot
  );

  return [value, observable.set] as const;
}

And there we are. The essential programming model of Broadstate, reconstructed using modern React primitives.

There's a subtle but important distinction here. We're no longer maintaining a local copy of the external value through an effect. We're giving React a mechanism for reading and subscribing to the source itself.

A subscription is not a render

Consider an application with three independently observable values.

const count = createObservable(0);
const theme = createObservable("light");
const user = createObservable(null);

Updating count doesn't need to notify subscribers of theme or user.

Compare this with a centralised store containing all three values. A conventional broadcast implementation notifies every subscriber, after which selectors determine whether their respective snapshots have changed.

count
3
3 items
£8.70
theme
Light
Nav
Code
user
Ade
Hi, Ade
Account
Independent observables
store.count
3
3 items
£8.70
store.theme
Light
Nav
Code
store.user
Ade
Hi, Ade
Account
One store, broadcast and select
Change a value. The same three components re-render in both; dashed rings are listeners that ran for nothing.

Both approaches can produce the same number of React renders while performing substantially different amounts of subscription work.

If a store has N subscribers but only K depend on the changed value, a broadcast-and-select implementation may perform N selector evaluations to discover K relevant updates. Independent observables can reduce the notification cost to K.

However, independent ownership introduces another problem.

Suppose two values represent the balance of two accounts. Transferring money between them requires changing both.

accountA.set(balance => balance - 50);
accountB.set(balance => balance + 50);

A synchronous observer can see the intermediate state, where money has disappeared from one account but hasn't arrived in the other.

A centralised store can represent the transfer as one atomic update.

accounts.set(({ a, b }) => ({
  a: a - 50,
  b: b + 50,
}));
Accounts
Current£500
Savings£500
Total£1,000
What the total was told, each time
Nothing yet
Not recommended: Two observables, two sets
Accounts
Current£500
Savings£500
Total£1,000
What the total was told, each time
Nothing yet
Recommended: One store, one set
Transfer £50. Both cards end on £1,000; only one total was ever told a number that didn't exist.

The smallest possible unit of state isn't necessarily the correct one.

Values that participate in the same invariant often deserve the same ownership boundary.

What 388 bytes doesn't buy you

The difficulty with writing a state manager isn't necessarily storing the state. It's defining the guarantees around reading and changing it.

Consider an object snapshot:

const person = createObservable({ age: 25 });

const current = person.getSnapshot();
current.age = 26;

person.set(current);

Nothing happens to the subscriptions. The reference hasn't changed.

This isn't a failure of Object.is. It's a violation of the store's snapshot contract.

Returning a newly allocated object from every getSnapshot call isn't the solution either. React needs the snapshot to remain referentially stable until its underlying value changes.

Then there's concurrent rendering. React can begin rendering against one version of an external store, interrupt that work and encounter another version before committing it.

Header£10
Line item£10
Subtotal£10
Pay £10
On screen
Not recommended: Reads the store during render
Header£10
Line item£10
Subtotal£10
Pay £10
On screen
Recommended: useSyncExternalStore
Start the render. The price changes after two parts; watch what each checkout commits.

useSyncExternalStore provides a supported mechanism for maintaining consistency across these reads, provided the store respects its contract.

Server rendering introduces another boundary. A module-level observable can outlive an individual request. State containing user-specific data must therefore be scoped appropriately, and hydration needs access to the snapshot used by the server.

None of these problems disappear because the implementation is small.

What I would do differently

I had a particularly interesting habit in 2020. Whenever I discovered a reusable programming pattern, I immediately wanted to turn it into a library.

I did something similar with Usable Query years later, introducing an opinionated abstraction over React Query when other engineers were perfectly comfortable consuming React Query directly.

Today, I'd probably keep Broadstate's underlying mechanism as a small utility until the application demonstrated a need for something more.

I'd introduce selectors when subscription granularity warranted them, transaction semantics when related values required them, and additional infrastructure only when the store needed to provide additional guarantees.

The interesting part of writing a state manager in under a kilobyte isn't proving that state management is simple.

It's discovering precisely where it stops being simple.

— Adenekan

Thoughts on this one?

Tell me what it made you think, or where you think I got it wrong.

Still working on the last 10%.0:00pm in london