mini-store
A state store for React component.
Motivation
When you want to share a component's state to another one, a commom pattern in React world is lifting state up. But one problem of this pattern is performance, assume we have a component in following hierarchy:
<Parent> <ChildA /> <ChildB /> <ChildC /></Parent>
ChildA
want to share state with ChildB
, so you lifting ChildA
's state up to Parent
. Now, when ChildA
's state changes, the whole Parent
will rerender, includes ChildC
which should not happen.
Redux do a good job at this situation throgh keeping all state in store, then component can subscribe state's changes, and only connected components will rerender. But redux
+ react-redux
is overkill when you are writing a component library. So I wrote this little library, It's like Redux's store without "reducer" and "dispatch".
Example
; Component { superprops; thisstore = ; } { return <Provider store=thisstore> <div> <Buttons /> <Result /> </div> </Provider> } @Component { const store = thisprops; const count = store; store; } { return <div> <button onClick=this>+</button> <button onClick=this>-</button> </div> ; } @Component { return <div>thispropscount</div> ; };
API
create(initialState)
Creates a store that holds the state. initialState
is plain object.
<Provider store>
Makes the store available to the connect() calls in the component hierarchy below.
connect(mapStateToProps)
Connects a React component to the store. It works like Redux's connect
, but only accept mapStateToProps
. The connected component also receive store
as a prop, you can call setState
directly on store.
License
MIT