Closed
Description
While the atom model fits with bottom-up approach (composing small atoms), we could create a big atom and select pieces out of it.
const bigAtom = atom({
num: 0,
str: 'hi',
bool: true,
obj: { a: 1, b: 2, arr: [3, 4, 5] },
})
const numAtom = atom(
get => get(bigAtom).num,
(get, set, update) => {
const prev = get(bigAtom)
const num = typeof update === 'function' ? update(prev.num) : update
set(bigAtom, { ...prev, num })
}
)
const [num, setNum] = useAtom(numAtom)
We can make this a hook. Let's try for a read-only atom.
const useSelector = (anAtom, selector) => {
const selectedAtom = useMemo(() => atom(get => selector(get(anAtom))), [anAtom, selector])
return useAtom(selectedAtom)[0]
}