Search code examples
reactjsreact-nativereact-state-managementrecoiljs

Is there a proven way to manage a collection of atoms in Recoil?


I'm testing Recoil and I need to manage a list of posts to display in the homepage.

My first idea was to make a big Atom with all the posts, but this seems a bit violent as we can edit posts directly on the homepage.

My second idea was to dynamically generate atoms with a prefix:

const onePost = (postId: string) => atom({
  key: 'post_' + postId,
  default: null,
  effects_UNSTABLE: [localStorageEffect('@post_' + postId)],
});

Then I realized that I was pretty a rookie playing with fire and that I shall ask people who are knowledgeable about Recoil on StackOverflow...


Solution

  • You can just use an array:

    const postIds = atom({
      key: 'postIds',
      default: [],
      effects_UNSTABLE: [localStorageEffect('postIds')],
    });
    

    This way you manage the list of ids in one atom and those ids can refer to different atomFamilys that hold the content data of the posts.