And is defined in two ways: get the hook from module instance, or use the public hook API.
module.useState
module.useActions or useModuleActions(module)
module.useComputed or useModuleComputed(module)
module.use or useModule(module)
useState
const{...}=module.useState()// useSelectorconstcount=module.useState(i=>i.count)// use custom compare fn, default is Object.isconst{count}=module.useState(i=> ({count:i.count},shallow)
You may use react-tracked by dai-shi to automatically generate selector.
Zoov also provide a adapter on react-tracked. But don't use this function as a replacement of module.useActions If you don't specify the state, the react-tracked will think that you are using the full state.
useActions
This hook will never trigger a rerender, you don't need to worry about the hooks performance.
useComputed
computed values are getter functions, the real thing under getter is a selector hook.
So, you should extract it when useComputed.
The computed hooks have some limitions, you can get more info from the Computed part
// π ββοΈοΌthe react-tracked will think you are using the full state
// and will always rerender on state change
const [, actions] = = useTrackedModule(module)
// πββοΈ: rerender only when count change
const [{ count }, actions] = useTrackedModule(module)
const {...} = module.useActions()
// π ββοΈ DO NOT get computed value in this way! may cause unexpected error.
const computed = module.useComputed()
if (xxx) {
// !! ERROR
return <>{computed.count}</>
}
// πββοΈ Use it like this.
const { ... } = module.useComputed()