0.0.3 • Published 6 years ago

react-shared-mutable-state v0.0.3

Weekly downloads
2
License
MIT
Repository
github
Last release
6 years ago

React Shared Mutable State

This project is built on a few beliefs:

  • React's state management is good.
  • Single Page Applications (SPAs) are not a silver bullet.
  • Multiple React trees are a sufficient (if not ideal!) architecture in many situations.
  • React's state management is good.

What does it do?

The ideal of having a single-atom-of-state that is used to render a single React tree is not possible in some architectures. This can be by legacy, or by choice. For these situations, having shared mutable state is necessary, and we want to manage it well.

Usage

Mount a single <Store/> component. This component owns the shared mutable state. It is an uncontrolled component, excepting one prop: defaultState.

Read shared mutable state anywhere in a React tree using <GetState />.

Example:

<GetState>
  {(sharedMutableState) => (
    <pre>
      {JSON.stringify(sharedMutableState, null, 2)}
    </pre>
  )}
</GetState>

Write shared mutable state anywhere in a React tree using <SetState />

<SetState counter={3} />

Other APIs

Keeping things declarative in a React tree was the initial idea. If this ideal cannot be satisfied, the escape hatches getState() and setState() are provided.

  • getState() returns the state of the mounted <Store /> component. If the <Store /> isn't mounted, the default React state shape of {} is returned.
  • setState() calls setState on the mounted <Store /> component. If the <Store /> isn't mounted, an error is thrown.

Caveats

Infinite loops?

It's probably easy to create infinite loops by composing <GetState /> and <SetState /> together. Lodash's isEqual has been used to prevent the most obvious possibilities, but I wouldn't rule them out completely.

Resetting state?

Re-rendering <Store defaultState={nextState} /> with a new key will reset it's internal state, same as rendering any component with a new key within any React tree!

Multiple stores?

YAGNI for now. I played with the ideas of multiple stores. The indirection and complexity introduced didn't seem to solve any problems particularly well. The increase in API surface area wasn't worth the theoretical organization or performance gains. Team-localized conventions for what is written to <Store /> is my preferred path forward, for now. It's React state, we can store whatever we want in it!

0.0.3

6 years ago

0.0.2

6 years ago

0.0.1

6 years ago