How would one structure deep nested state tree with RecoilJS? Should I have every branch as separate atom or something?
If you don't split the structure in atoms, you won't leverage the most important Recoil feature: updating just the UI components subscribed to the atoms. If you have a single atom, every time you update the atom all the UI re-renders. There is no difference between using a React Context and using Recoil if you don't split the structure in atoms.
Instead, splitting the data in atoms and atom families (and selectors, and selector families) allows you to leverage Recoil at its best. Only the components subscribed to specific atoms re-render when the atom updates!
What is the difference between atoms and atom families? Why is so important to leverage both of them and not only atoms (eventually with selector families)?
Nested atoms and atom families have one thing in common: they allow you to manage nested data structures, for example, with mileage data stored in an atom:
// carsMileage atom structure
{
teslaModel3: {
miles: 50.000
},
chevroletCorvette: {
miles: 100.000
}
}
only the components that are subscribed to the carsMileage
atom re-render on atom changes, but you can't have a component that shows only teslaModel3
's mileage that doesn't re-render when chevroletCorvette
's mileage changes (nor with selector families). Instead, an atom family that contains the mileage only
{
miles: 50.000
}
managed through an atom family with two keys (teslaModel3
and chevroletCorvette
) allows you to have components subscribed to the atom they are interested too. Updating teslaModel3
mileage does not cause a ChevroletCorvetteData
components re-render. Please note that from a data perspective, both an atom and an atom family are just nested objects, nothing more.
Just to be exhaustive: the only disadvantages of an atom family is that Recoil doesn't help you remember the keys (teslaModel3
and chevroletCorvette
) you used to store data... You have to store the keys in another atom otherwise you are out of luck.
In the end: no, don't use a single atom with all the data, you could avoid Recoil at all if you want to go this way 😊
© 2022 - 2024 — McMap. All rights reserved.