React state management
provider-kit
Structured, type-safe state for React.
provider-kit-publicUsed by
- Pebbler® for Telegram
- Pebbler® on World
- Bridge
- Asset One
- Brain Bus
- UnScrewed!
- Picture Jam
- Match & Win
- Color Jam
I built provider-kit because I wanted a consistent way to share state across React components as my applications grew. State needed to stay strictly typed, updates needed a clear structure, and adding another piece of shared state shouldn’t mean adding another nested provider to main.tsx.
The library brings those decisions into a reusable package, used across applications including Pebbler, Bridge, and Asset One. Its source is now public on GitHub, together with the tests and documentation that explain its behavior.
Keeping shared state organised
React context provides a useful foundation for shared state. As an application gains more independent pieces of state, though, each context can bring its own provider, hook, types, and update conventions. I wanted a repeatable way to define those pieces without making the application’s entry point responsible for wiring them all together.
My approach was to group state into named slices and let a factory create the contexts, provider, and hook. Each slice keeps its own context internally. The application mounts one provider component, while the library handles the composition behind it.
Defining state once
I use Zod schemas to describe each slice. TypeScript infers the state shape from that definition, and the same schema validates initial values and changed state at runtime. This keeps the runtime rules and the types components use connected, rather than maintaining two separate descriptions of the same data.
In this example, filters and selection are independent slices. The factory returns a SlicesProvider and a useSlice hook bound to that configuration. The hook knows that filters has a string query and a numeric page; an unknown slice name or an incorrectly typed patch is a compile-time error.
import { createSlicesProvider } from '@bridge-applications/provider-kit';
import { z } from 'zod';
const { SlicesProvider, useSlice } = createSlicesProvider({
filters: {
schema: z.object({
query: z.string().default(''),
page: z.number().int().positive().default(1),
}),
initial: {},
},
selection: {
schema: z.object({ ids: z.array(z.string()) }),
initial: { ids: [] },
},
});
function Search() {
const { state, setSlice } = useSlice('filters');
return (
<input
aria-label="Search tasks"
value={state.query}
onChange={(event) =>
setSlice({ query: event.target.value, page: 1 })
}
/>
);
}
export function App() {
return <SlicesProvider><Search /></SlicesProvider>;
}A complete, simplified example using the public API. The factory is created outside render; the filters schema supplies defaults and validates updates.
Public API and usage referenceMaking ownership and lifetime explicit
The factory creates stable contexts once, outside render. Ordinary parent renders then preserve the mounted provider’s slices and child state. This is an important detail: recreating the factory during render would create a different provider component and reset that subtree.
Each provider mount owns independent state. Separate factories are isolated even when they use the same slice names, so a hook cannot accidentally read another factory’s data. This makes ownership local to the part of the application that mounts the provider. When a reset is intentional, such as switching accounts, changing the provider’s React key starts a fresh subtree.
Keeping updates predictable
Updates use partial object patches with a shallow merge. Changing the search query can also reset the page in one update, as the example shows. Nested objects and arrays are replaced as complete fields, which keeps the update rule explicit. When the next value depends on previous state, a functional patch reads the latest queued state, including earlier updates in the same batch.
The schema checks the resulting changed state before it becomes the next value. Schemas and updater functions must be pure and synchronous, because React can invoke them more than once during development checks. Defaults and refinements fit this model; asynchronous work belongs outside the schema.
Validation failures have a deliberate boundary. Invalid initial state fails during factory creation; an invalid update reaches a React error boundary during update processing. Expected input errors, such as a user entering an invalid form value, should be handled before committing state. The library’s validation protects the state contract rather than supplying form feedback.
Choosing a focused scope
Separate contexts limit update notifications to the changed slice. Every consumer of that slice still receives the update, even if it only reads one field, and parent renders can still render their children. Empty or shallowly unchanged patches preserve state identity. These choices suit shared UI state while keeping the rendering model close to React’s own behavior.
I kept the package focused on application state: filters, selections, upload queues, and similar concerns. It does not provide request caching, persistence, field selectors, or transactions across slices. Those requirements deserve their own solutions. Keeping the boundary clear makes the package easier to reason about and lets each application choose the other tools it needs.
From application code to a public package
Reusing provider-kit across products made the behavior of the shared layer worth documenting and checking independently. The public source release includes tests for validation, queued updates, provider isolation, rendering behavior, and server rendering. Compile-time checks exercise both accepted and rejected types.
The repository also checks the packed package in a separate consumer, covering ESM imports, TypeScript declaration resolution, and browser bundling. That verifies what an application actually imports, alongside the implementation tests. React and Zod remain peer dependencies, and the library supplies no global mutable state store.
I’m sharing the source so other developers can inspect the design, try the examples, and contribute improvements through the repository. The README explains the API and its constraints, while the architecture notes go deeper into state ownership, updates, and validation. The aim remains the one I started with: a clean way to grow shared state while keeping its types and behavior explicit.