@sourcebug/amos
Version:
A decentralized state manager for react
72 lines (71 loc) • 2.57 kB
TypeScript
import { useLayoutEffect } from 'react';
import { Dispatch, Selectable, Store } from './store';
export declare const useIsomorphicLayoutEffect: typeof useLayoutEffect;
/**
* use context's store
*
* @stable
*/
export declare function useStore(): Store;
export declare function useDispatch(): Dispatch;
export declare type MapSelector<Rs extends readonly Selectable[]> = {
[P in keyof Rs]: Rs[P] extends Selectable<infer R> ? R : never;
};
/**
* Get the selected states according to the selectors, and rerender the
* component when the selected states updated.
*
* A selector is a selectable thing, it could be one of this:
*
* 1. A pure function accepts `store.select` as the only one parameter
* 2. A `Selector` which is created by `SelectorFactory`
* 3. A `Box` instance
*
* If the selector is a function or a `Selector`, the selected state is its
* return value, otherwise, when the selector is a `Box`, the selected state is
* the state of the `Box`.
*
* `useSelector` accepts multiple selectors, and returns an array of the
* selected states of the selectors.
*
* @example
* ```typescript
* const [
* count, // 1
* doubleCount, // 2
* tripleCount, // 3
* ] = useSelector(
* countBox, // A Box
* selectDoubleCount, // A pure function
* selectMultipleCount(3), // A Selector
* );
* ```
*
* The selectors' result is cached, which means:
*
* 1. If a selector's dependencies is not updated, it will not be recomputed.
* 2. If all the results of the selectors are not changed, the component will
* not rerender.
*
* If the selector is a `Selector`, it will be recomputed:
*
* 1. if it has no `deps` function, when its parameters changes, or the state
* of the boxes it depends on changes
* 2. else, when the return value of the deps function changes. The return
* value should always be an array, and the compare method is compare each
* element of it.
*
* and it will be marked as changed:
*
* 1. if it has no `compare` function, when the result is not strict equals to
* the previous result.
* 2. else if the compare function returns `false`.
*
* If the selector is a pure function, the cache strategy is same to a
* `Selector` without parameter and without `deps` and `compare` function. If
* the selector is a `Box`, the cache strategy is same to a `Selector` without
* parameter and with `deps` as `false` and without `compare` function.
*
* @param selectors a selectable array
*/
export declare function useSelector<Rs extends Selectable[]>(...selectors: Rs): MapSelector<Rs>;