Immutable Context: state management in React with Hooks, Context and Immer (and TypeScript)

I made a state management library for React with Hooks, Context and Immer (and TypeScript): Immutable Context. See also an example.

Basically you write a TypeScript type for your state, supply an initial state. Then via context/hooks you can access the current state or update it. A complete(!) example looks like:

type CounterType = { count: number };

const { StateProvider, useImmutableContext } = createImmutableContext<
>({ count: 0 });

A component, using hooks to wire up. The update increment function could easily be moved to another file, unit tested etc.

const Counter = () => {
  const { dispatch, state } = useImmutableContext();
  const increment = () =>
    dispatch(s => {
  return <button onClick={increment}>Count: {state.count}</button>;

Then to use, it is just:

const App = () => (
    <Counter />

The updates work by just applying a function to the state. However it leverages Immer so you get immutability out of the box while being able to just 'mutate' potentially deeply nested things.

It should have many of the advantages of Redux in a fraction of the code. In fact your updates can live in separate files, be unit tested straightforwardly yet be very simply integrated with your components via hooks.

PS It is a prototype, if you like the idea I think the best current way to do something like it is using MobX State Tree which includes many more batteries(!)

See all updates