Skip to content

Instantly share code, notes, and snippets.

@jtmthf
Created January 6, 2022 08:15
Show Gist options
  • Save jtmthf/b1f2fd76ebf56e6ff373bc0c0a4f68c3 to your computer and use it in GitHub Desktop.
Save jtmthf/b1f2fd76ebf56e6ff373bc0c0a4f68c3 to your computer and use it in GitHub Desktop.
import { Atom } from 'jotai';
import { selectAtom, useAtomValue} from 'jotai/utils';
import { useMemo } from 'react';
import { createTrackedSelector } from 'react-tracked';
type ResolveType<T> = T extends Promise<infer V> ? V : T
export function useSelectAtom<Value, Slice>(
atom: Atom<Value>,
selector: (v: ResolveType<Value>) => Slice,
equalityFn: (a: Slice, b: Slice) => boolean = Object.is
): ResolveType<Slice> {
const selectedAtom = useMemo(() => selectAtom(atom, selector, equalityFn), [atom, selector, equalityFn]);
return useAtomValue(selectedAtom)
}
export function createAtomSelector<Value>(atom: Atom<Value>): <Slice>(selector: (value: Value) => Slice) => Slice {
return <Slice>(selector: (v: ResolveType<Value>) => Slice) => {
return useSelectAtom(atom, selector);
}
}
export function createTrackedAtom<Value>(atom: Atom<Value>) {
return createTrackedSelector(createAtomSelector(atom));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment