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

Introducing the useAtomState hook #144

Open
njordhov opened this issue Dec 31, 2019 · 0 comments
Open

Introducing the useAtomState hook #144

njordhov opened this issue Dec 31, 2019 · 0 comments

Comments

@njordhov
Copy link

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]);
}
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant