Skip to content

Latest commit

History

History
77 lines (55 loc) 路 1.78 KB

custom-useatom-hooks.mdx

File metadata and controls

77 lines (55 loc) 路 1.78 KB
title nav
Custom useAtom hooks
5.03

This page shows the ways of creating different utility functions. Utility functions save your time on coding, and you can preserve your base atom for other usage.

utils

useSelectAtom

import { useAtomValue } from 'jotai'
import { selectAtom } from 'jotai/utils'

/* if an atom is created here, please use `useMemo(() => atom(initValue), [initValue])` instead. */
export function useSelectAtom(anAtom, keyFn) {
    return useAtomValue(selectAtom(anAtom, keyFn))
}

// how to use it
useSelectAtom(
    useMemo(() => atom(initValue), [initValue]),
    useCallBack((state) => state.prop, [])
)

Please note that in this case keyFn must be stable, either define outside render or warp with useCallback.

useFreezeAtom

import { useAtom } from 'jotai'
import { freezeAtom } from 'jotai/utils'

export function useFreezeAtom(anAtom) {
    return useAtom(freezeAtom(anAtom))
}

useSplitAtom

import { useAtom } from 'jotai'
import { splitAtom } from 'jotai/utils'

export function useSplitAtom(anAtom) {
    return useAtom(splitAtom(anAtom))
}

integrations

useFocusAtom

import { useAtom } from 'jotai'
import { focusAtom } from 'jotai/optics'

/* if an atom is created here, please use `useMemo(() => atom(initValue), [initValue])` instead. */
export function useFocusAtom(anAtom, keyFn) {
    return useAtom(focusAtom(anAtom, keyFn))
}

// how to use it
useFocusAtom(anAtom) {
    useMemo(() => atom(initValue), [initValue]),
    useCallBack((optic) => optic.prop('key'), [])
}

CodeSandbox

Please note that in this case keyFn must be stable, either define outside render or warp with useCallback.