Hooks

There are 4 three basic hooks in zoov module.

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()

// useSelector
const count = module.useState(i => i.count)

// use custom compare fn, default is Object.is
const { count } = module.useState(i => ({ count: i.count }, shallow)

You may use react-tracked by dai-shi to automatically generate selector.

import { createTrackedSelector } from 'react-tracked';

const useCounterModuleState = createTrackedSelector(CounterModule.useState);

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.

// πŸ™…β€β™‚οΈοΌš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)

useActions

This hook will never trigger a rerender, you don't need to worry about the hooks performance.

const {...} = module.useActions()

useComputed

computed values are getter functions, the real thing under getter is a selector hook.

So, you should extract it when useComputed.

// πŸ™…β€β™‚οΈ 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()

The computed hooks have some limitions, you can get more info from the Computed part

Last updated