react-atom icon indicating copy to clipboard operation
react-atom copied to clipboard

Introducing the useAtomState hook

Open njordhov opened this issue 4 years ago • 0 comments

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

njordhov avatar Dec 31 '19 22:12 njordhov