Recoil.js is being designed by facebook apparently to replace redux so I figured I’d take a look.
My sample Codesandbox
Atoms – most basic for of state that can be shared amongst components and or selectors. It requires a “key” which must be unique and to initialize with a value(s) use default.
|
1 2 3 4 |
const marginTopState= atom({ key: 'marginTopState', default: 10, }); |
useRecoilState – Used to read and write an atom from a component.
Selectors – a pure function that will basically just return a computed value based on atom(s) and/or other selectors. By default, selectors are not writable and so can not alter the atoms/selections within it; only use it to provide its produced computed value. (get)
|
1 2 3 4 5 6 7 8 9 10 |
const marginTopComputedState = selector({ key: 'marginTopComputedState', get: ({get}) => { const marginTopValue = get(marginTopState); const unit = 'px'; // would use template literals here but my code highlighting // plugin I used for the site breaks :( return marginTopValue+unit; }, }); |
useRecoilValue – used to get/use the computed value from a selector.
|
1 |
const computedMarginTopLabel = useRecoilValue(marginTopComputedState); |
Creating “n” amount of atoms
Sometimes we need an unknown amount of state atoms in an app. One way is to create a function that will returned a memorized atom based on an ID. We memorize it that way if it is the same ID we use the already made atom and return that instead of regenerating the atom.
For example:
|
1 2 3 4 5 |
export const itemWithID = memoize(id => atom({ key: "item"+id, // done this way because tilde strings breaks my code highlighting plugin :( default: "" })) |
Then we can use it in components like below:
|
1 2 3 4 |
function SomeComponent({id}){ const [itemState, setItemState] = useRecoilState(itemWithID(id)); return ... } |