Recoil: Best way to use atomFamily/selectorFamily

Created on 10 Jun 2020  路  5Comments  路  Source: facebookexperimental/Recoil

Hi there! Really love working with recoil, it's been fun implementing it in a lil documents app I'm building.

I am trying to get my head around the best ways to model data with recoil. Currently I have atoms set up such as:

const items = atom<EntityState<SingleItem>>({
  key: 'items',
  default: {
    ids: [],
    entities: {},
  },
});

And when I'm adding a new item, it generates an ID and pushes them to the array, then the single item lives in entities[id] = item.

I feel like things would be better if I used atomFamily, but I am not clear on how to get a list of all the ids within a type of atom/family.

Additionally, if I have the base atom of the item, which contains the entries and ids, does it make sense to then use atomFamily/selectorFamily to use that as the source of data? In that situation, would anything that did something like const singleItem = useRecoilValue(itemsFamily(id) subscribe to just the specific item?

Thanks for any guidance!

question

Most helpful comment

What I like to do in this situation where you need to keep track of all ids is to have an atom of ids and entities, and an atomFamily that given an id returns the entity from that atom. This lets you subscribe to specific ids, and if you need more than one you can create a selectorFamily that given a collection of ids it aggregates the atoms into a singular value.

All 5 comments

What I like to do in this situation where you need to keep track of all ids is to have an atom of ids and entities, and an atomFamily that given an id returns the entity from that atom. This lets you subscribe to specific ids, and if you need more than one you can create a selectorFamily that given a collection of ids it aggregates the atoms into a singular value.

I had the same question.

Here's my example implementation of @Shmew's suggestion (this was before atomFamily was in the released library however so I just use a custom utility).

In addition, you can also use waitForAll to help aggregate without needing a custom selector.

As for as I'm concerned, I'm not clear on when using atomFamily & selectorFamily vs atom and selector. What are the major differences? It looks like an equivalent to "combineReduer" for redux, am I missing something?

Families just represent a collection of atoms or selectors based on some parameter. They are useful for passing parameters into selector functions or for creating more granular atoms, since atoms and selectors are the unit of resolution for controlling component updates.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

karevn picture karevn  路  3Comments

jamiebuilds picture jamiebuilds  路  3Comments

atanasster picture atanasster  路  3Comments

adamkleingit picture adamkleingit  路  4Comments

pesterhazy picture pesterhazy  路  4Comments