preface
The React project of the author was developed on the basis of UMI and mainly used the @umiJS/plugin-Model provided by UMI as the state management tool. However, in the process of project development, global state was sometimes used outside components. The simple way is to store the state to be used separately in localStroage and get the call in the corresponding place. This way is tedious, so I came up with the idea of writing a state management tool myself.
Plugin-model stores all the data into context when UMI starts, and deviates from the normal rendering flow, and uses the custom useModel for data acquisition and update. Because of the abnormal rendering flow, the data cannot be obtained when useContext is called in useModel. Therefore, plugin-Model adopts the publish and subscribe mechanism. When useModel is called, the corresponding callback function is written.
Inspired by plugin-model, we can abandon context-based data management, directly use JS original objects for management, and define relevant hooks. When data is updated, we can directly notify the modification through the publish and subscription mechanism. As react is not involved in data management, So you can use the data directly outside of react initialization.
The basic code has been implemented and is available on Github below.
store-hook
demo
use
The createModule initializes a state module. After initialization, a custom hook method is returned. You can use react Hook to call the state, access method properties, or use state data
State definition
const useCustomStore = createModule({
/ /... Related to the definition
})
Copy the code
Direct call
// Get attributes
const a = useCustomStore.state.a;
// Call the method
const fn = useCustomStore.fn();
const { fn } = useCustomStore;
fn();
Copy the code
Hook form call
// Use the react component as a hook
const App = () = >{
const store = useCustomStore();
return null;
}
// Support selector, listen for partial data, performance optimization
const App = () = >{
const customStore = useCustomStore((store) = >({
a: store.state.a,
fn: store.fn
}));
return null;
}
Copy the code
conclusion
This program is just an idea of my own, the implementation of the basic code, there are a lot of boundary cases are not considered, and has not been published on NPM, if you have better ideas, welcome to discuss in the comments section.