react-use-global
React hook for using global state without unnecessary renders.
Concept:
- Create an global state object with initial value.
- Subscribe a component to any part of that object.
- The component will only re-render if that part of the state changes.
Install:
npm install react-use-global --save
Use:
API | usage | description |
---|---|---|
function createGlobal | (any initialState) => function useGlobal | Imported from 'react-use-global'. Takes initial state value, returns useGlobal function. |
function useGlobal | (string path) => [any state, function setState] | Takes a path (e.g. 'user.settings.nightMode'), returns the value and a function to set that value. Just like React's useState. |
Example:
const initialState = count: 42 input: "wow this is cool" show: count: false input: true const useGlobal = const Toggles = { const showCount setShowCount = const showInput setShowInput = return <div> <input type="checkbox" checked=showCount onChange= /> <label>show count</label> <input type="checkbox" checked=showInput onChange= /> <label>show input</label> </div> } const Count = { const count setCount = const showCount = if !showCount return null return <div> <span>count</span> <button onClick= >+</button> <button onClick= >-</button> </div> } const Input = { const input setInput = const showInput = if !showInput return null return <div> <input value=input onChange= /> </div> } const App = { return <div> <Toggles/> <Count/> <Input/> </div> ;} ;
License
MIT