|
| 1 | +# flipstate |
| 2 | + |
| 3 | +*Flip to any state* |
| 4 | + |
| 5 | +React v16.3 Context API solved prop drilling but produced a huge unmanagable state tree. `flipstate` solves this by decomposing `Context.Provider` into smaller state. Easily manage state per component, but keep the power of having all the state in a single place. |
| 6 | + |
| 7 | +Getting started |
| 8 | +--------------- |
| 9 | +Here is a simple counter application. |
| 10 | +```js |
| 11 | +import React from 'react' |
| 12 | +import {render} from 'react-dom' |
| 13 | +import createState from 'flipstate' |
| 14 | + |
| 15 | +const { |
| 16 | + StateProvider, |
| 17 | + GlobalState, |
| 18 | + addState |
| 19 | +} = createState() |
| 20 | + |
| 21 | +const CounterState = addState('Counter', { |
| 22 | + count: 0, |
| 23 | + increment({count}, amount) { |
| 24 | + return { |
| 25 | + count: count + amount |
| 26 | + } |
| 27 | + }, |
| 28 | + decrement({count}, amount) { |
| 29 | + return { |
| 30 | + count: count - amount |
| 31 | + } |
| 32 | + } |
| 33 | +}) |
| 34 | +const Counter = () => |
| 35 | + <CounterState>{({count, increment, decrement}) => |
| 36 | + <> |
| 37 | + <p>count: {count}</p> |
| 38 | + <button onClick={() => increment(1)}>+</button> |
| 39 | + <button onClick={() => decrement(1)}>-</button> |
| 40 | + </> |
| 41 | + }</CounterState> |
| 42 | + |
| 43 | +render(<StateProvider> |
| 44 | + <Counter/> |
| 45 | +</StateProvider>, document.getElementById('entry')) |
| 46 | +``` |
| 47 | + |
| 48 | +Highlights |
| 49 | +---------- |
| 50 | + * added state are just render prop components |
| 51 | + * `StateProvider` is the Context API provider and works in the same way. Only state components that are decendents of `StateProvider` will receive updates (but don't need to be direct children) |
| 52 | + * modules can export state for others to consume. Think `AuthState` that updates when user logins. |
| 53 | + * compose states from multiple components using https://github.com/gnapse/render-props-compose |
| 54 | + * state is composed of data + actions |
| 55 | + * actions return an update to merge into the state |
| 56 | + * actions can be `async` |
| 57 | + * use dynamic import to code split new data/actions/state/components |
| 58 | + * supports preact, just import 'flipstate/preact'. Requires https://github.com/valotas/preact-context |
| 59 | + * incoming dev tool which will allow you to flip to any state |
0 commit comments