Skip to content
This repository was archived by the owner on Sep 14, 2023. It is now read-only.
This repository was archived by the owner on Sep 14, 2023. It is now read-only.

Introducing the useAtomState hook #144

@njordhov

Description

@njordhov

I am using react-atom in multiple projects, often starting with React.useState() then upgrading to atoms. The useAtomState() hook below makes it take only a few keystrokes to replace useState with a react-atom. It has the same return signature as useState but takes an Atom.

Perhaps it could be added to the distribution? It would make it (even) easier for React devs to start using react-atom and upgrade their existing react hook codebase.

function useAtomState (atom) {
  const state = useAtom(atom);
  const setState = useCallback ((obj) => {
    swap(atom, (typeof obj === 'function') ? obj : () => obj)
  }, [atom]);
  return ([state, atom ? setState : null]);
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions