react-global-hook
Easy state management for react & react-native using hooks. it's useful for global state management and complex components state
React-global-hook V2 uses the React.context
TOC
Install
npm i react-global-hook@next --save
yarn add react-global-hook@next
createStore
; const initialState = counter: 0; const actions = { const count = ; } { const count = if count <= 0 return; ; }; /** * The initializer run when Provider render */const initializer = ...state counter: const store = ;const useGlobal = ; const OtherComp = { const state actions = ; // Will update based on changes to counter return <p>Count:statecounter</p>;}; const Container = { const actions = storeactions; // will not update return <div> <button type="button" onClick=actionsdecrease> Decrease </button> <button type="button" onClick=actionsincrease> Increase </button> <OtherComp /> </div> ;}; const App = <Provider store=store> <Container> <Provider>
classComponents
if you want to use store in class component follow this approach
{ const increase decrease count = thisprops; return <p onMouseEnter=increase onMouseLeave=decrease> count </p> ; } storeTestComponent;
useLocalStore
Use this instead of useReducer
; const App = { const counter actions = ; return <div> <p> Count: counter </p> <button type="button" onClick=actionsincrease> Increase </button> </div> ;};
Store
; const store = ; const getState actions setState useState addListener = store;
setState
Set partial state
;
addListener
Add an event listener. Listener run when a state update
//Run when counter update { console;}store;
actions
gives bound actions
storeactions;
Persist
For persist state add your function to listener
{ asyncStorage}store; // Whenever the token and username change, this function will call.
Performance
Avoid unreasonable repetition of setState for better performance. Because after each setState, every component that is connected with hook will be rendered again and every function added to listener will be run again. For Example
// Bad { ; ; };
// Good { ; };