Recoil icon indicating copy to clipboard operation
Recoil copied to clipboard

consider adding `useRecoilMemo`

Open ianstormtaylor opened this issue 3 years ago • 2 comments

I find myself in a situation often where a component needs to build up some derived state from a series of different atoms/selectors—this may even be looping over an array of atoms/selectors. And to do that I'm forced to create a new selector that represents this components derived state (to have access to get in a context where looping is fine).

Instead, it would be nice if there was a useRecoilMemo which was similar to useMemo except it received ({ get }) as a parameter. So you could do complex aggregations right inline without having to define these one-off atoms/selectors.

Here's a very simplified example:

const Component = ({ users }) => {
  const data = useRecoilMemo(({ get }) => {
    return users.map(user => get(userProfileSelectorFamily(user.id)))
  }, [users])
  
  return <div>{data...}</div>
}

But these aggregations are often much more complex.

ianstormtaylor avatar Apr 23 '21 14:04 ianstormtaylor

This looks similar to #317, and we have a proposed implementation in #319 for a map() method for atoms/selectors which allow inline derived state. Super convenient. The problem there is determining a unique key for the implicit selector. Using a hook, as proposed here, sounds like a nifty way to solve that problem. Would be interesting if you want to toss together a reference implementation!

drarmstr avatar Apr 23 '21 19:04 drarmstr

Prototype started by @alanasim, some feedback remaining.

drarmstr avatar Aug 18 '22 19:08 drarmstr