react model Use the hooks manage your global state
- lightweight Based on the React hooks to manage all of your state, no other dependencies
- faster Automatically track the change of the state, only after the state change to re-render the component
- easy Only three steps can be used directly, use only the react
- typescript Make you write the React code more easily
$ npm i -S remode
## or
$ yarn add remode
- create the model
A file is a model, logic clearer, more convenient maintenance
// src/models/user.ts
import { useState } from 'react';
// This is a generic hooks
const usePersistCallback = <T extends Function>(callback: T) => {
const cbRef = useRef<Function>();
cbRef.current = callback;
return useCallback((...args) => cbRef.current!(...args), []);
};
function user() {
const [userInfo, setUserInfo] = useState(null)
// Function after persistent here, won't lead to additional rendering
const login = usePersistCallback(() => {
// login logic
})
return {
login,
userInfo
}
}
- init the model
Each model has its own namespace
// src/models/index.ts
import initModels from 'remode';
import userModel from './user';
const Model = initModels({
user: userModel,
// otherNamespace: otherModel
})
export default Model
- use the model
// src/index.tsx
import ReactDOM from 'react-dom'
import Model from './models';
// The root element mount Provider once
ReactDOM.render(
<Model.Provider>
// other element
</Model.Provider>,
document.getElementById('root')
)
// src/pages/login.tsx
import Model from '../models';
const LoginPage = () => {
const { userInfo, login } = Model.useModel('user')
// other logic
}
You can use a logger to debug your state, add the code the file src/models/index.ts
;
then you can see the output of the state in the console
if(process.env.NODE_ENV === 'development') {
Model.subscribe(require('remode/logger'))
}