Computed

The computed is an inferred value from the state object.

All the computed value are lazy loaded, which means, the getter function will not be called unless you use the computed value in a React Component.

const { useComputed: useCounterComputed } = defineModule({ count: 0 })
  .computed({
    doubled: (state) => state.count * 2,
  })
  .build();
  
// Once the computed result changes
// the component will get rerendered.
function Component() {
  const { doubled } = useCounterComputed()
  return <div>{doubled}</div>  
}

The implementation

The getter function

Zoov uses proxy-compare to get the dependancy list of a getter function. The getter function will try to return the cached result if dependancy is not changed.

The hooks

Zoov uses zustand's useState hook with a memoized selector. If the computed result turned out to be strictly equalled, the component will not be rerendered. Otherwise, it will be force updated to retreive the latest computed avlue.

Limitations

Because computed use zustand selector under the hood. If the getter function return an object, the component will be rerenderd everytime the result changes.

Last updated