react-one
A single store, single action, global state management system for React apps.
installation
npm install react-one --save
or
yarn add react-one
Usage
;
Wrap the root of your app with the Provider
component and pass it an initialState
object.
const INITIAL_STATE = num: 0 ;... { return <Provider initialState=INITIAL_STATE onSetState= console > <App /> </Provider> ;}
Connect any of your app's child components to the global store with the connect
higher order component. Any connected component will have state
and setState
passed as props. Treat them as a global this.state
and this.setState
. This means you can call setState
in one component and have that update reflected in another connected component without prop drilling or callbacks. This also means the global state will persist even when a connected component is unmounted.
Component { let state setState = thisprops; return <> <button onClick= /> <h1>statenum</h1> </> ; } Example;
If you want to call multiple setState
s that rely on the previous state in the same block of code, you will probably have to use a callback or functional setState
because setState
, like this.setState
, updates state asynchronously.
// this one line is equivalent; // state.num = 2// to these two;; // state.num = 2 // this won't work;; // state.num = 1 // this is an exception;; // state.num = 2
Example
;;; const INITIAL_STATE = num: 0 ; Component { return <Provider initialState=INITIAL_STATE onSetState= console > <div> <Buttons /> <Num /> </div> </Provider> ; } Component { let state setState = thisprops; return <div> <button onClick= >+</button> <button onClick= >-</button> </div> ; } Buttons = ; // if this were in another file, export default connect(Buttons) Component { let state = thisprops; return <h1>statenum</h1>; } Num = ; // if this were in another file, export default connect(Num) ReactDOM;
Running the example
git clone https://github.com/MiLeung/react-one.git
cd react-one
npm i
npm start
Then in another window
cd react-one/example
npm i
npm start