react-globally
Gives you setGlobalState, so you can set state globally
What is this?
This lib gives you two things:
- setGlobalState: A function with the exact same API of
setState
but that sets the state globally - globalState: The global state that's updated when you call
setGlobalState
You receive both via props wrapping any component with the withGlobalState
function.
To use withGlobalState
, you will have to wrap your app with a Provider
that receives the initial state.
This way you can use setState
to manage the local state of a Component and setGlobalState
to manage the global state with the same API.
Key benefits
- No need to learn a new API: If you know how to use
setState
, you know how to usesetGlobalState
- Simplicity: Just wrap your components with a function and that's it
- Progressive: Start with
setState
, if there's the need, change it tosetGlobalState
Installation
You can install it via npm:
npm install --save react-globally
CDN
If you prefer to exclude react-globally from your application and use it globally via window.ReactGlobally, the react-globally package provides single-file distributions via unpkg:
<!-- development version --> <!-- production version -->
Usage
First you have to wrap your app with the Provider
giving it the initial state:
// index.js const initialState = counter: 0 { return <div> <CounterControls /> <CounterInfo /> </div> } ReactDOM
Then you wrap the components that should have a global state with withGlobalState
:
// CounterControls.js Component { thisprops } { thisprops } { thisprops } { return <div> <button onClick=thisincrement>Increment</button> <button onClick=thisdecrement>Decrement</button> <button onClick=thiszero>Set to Zero</button> </div> } CounterControls
You can access and set the global state anywhere in the tree, and it works with stateless functional components too, since it's just props:
// CounterInfo.js const CounterInfo = { return <div> The counter value: propsglobalStatecounter <button onClick= props>Set to 100</button> </div> } CounterInfo
Reusing your code
You can extract your setState
and/or setGlobalState
calls to pure functions, reusing and testing them in isolation.
See this tweet from Dan Abramov.