Search code examples
recoiljs

Retrieve an atom/selector by key (string)?


When using Recoil.js, one creates an atom by handing atom() an object that include a key (a string):

const textState = atom({
  key: 'textState', // unique ID (with respect to other atoms/selectors)
  default: '', // default value (aka initial value)
});

Later on one can get the value (and a setter) by handing the thing that atom() returns to something like useRecoilState:

function TextInput() {
  const [text, setText] = useRecoilState(textState);

It's fine that I need to first create the atom using atom() but after that I'd love to get the value (and the setter) using the string key. I'm imagining something like this:

function TextInput() {
  const [text, setText] = useRecoilState('textState');

The use case for this is that I could then create all my atoms (and selectors) in places that make sense (i.e., higher up the hierarchy) and then have components access that state without having to include the atoms from the file that originally created them.

Is it possible to get the value/setter function for Recoil atoms/selectors using the key (the string/text) instead of having to hand useRecoilState() (etc) the thing returned from atom()?


Solution

  • No it's not possible. The value that the call to atom() returns is a reference to the state, that the useRecoil... hooks need to access it. This also wouldn't work with atomFamilies which need a parameter to access a specific atom.

    I am also not sure what the benefit would be. You can still create the atoms somewhere up in the hierarchy if you want to. I am also not sure what you mean by "without having to include the atoms from the file that originally created them". What would be the problem with that?

    The whole idea of Recoil is to have a state tree orthogonal to your component tree, so there is no need for creation higher up in the hierarchy. Atoms are created where they are needed during runtime. It feels like you want to have more of a redux like pattern with atoms being created in one place up in the component tree, which defies this core idea of recoil that is setting it apart from the more flux like state management patterns.