Skip to content

[Tips] useSelector equivalent #36

Closed
@dai-shi

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]
}

Metadata

Assignees

No one assigned

    Labels

    has snippetThis issue includes code snipppets as solutions or workaroundsneeds infoFurther information is requested

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions