In Recoil, observing multiple atoms can be achieved by using selector. Selector is a core concept in Recoil that allows you to create a derived state which can depend on one or more atoms or other selectors.
Step 1: Define your atoms
First, define atoms that will store your application's state.
javascriptimport { atom } from 'recoil'; const firstNameAtom = atom({ key: 'firstName', default: '', }); const lastNameAtom = atom({ key: 'lastName', default: '', });
Here we define two simple atoms: firstNameAtom and lastNameAtom, used to store the user's first and last name.
Step 2: Create a selector to observe these atoms
Next, create a selector that depends on the atoms defined above.
javascriptimport { selector } from 'recoil'; const fullNameSelector = selector({ key: 'fullName', get: ({ get }) => { const firstName = get(firstNameAtom); const lastName = get(lastNameAtom); return `${firstName} ${lastName}`.trim(); }, });
In this fullNameSelector, we use the get function to retrieve the current values of firstNameAtom and lastNameAtom, then combine them into a full name.
Step 3: Use the selector in a component
Finally, implement this selector in a React component to display or handle data.
javascriptimport { useRecoilValue } from 'recoil'; import React from 'react'; function FullName() { const fullName = useRecoilValue(fullNameSelector); return <div>Full Name: {fullName}</div>; } export default FullName;
In this FullName component, we use useRecoilValue to subscribe to fullNameSelector's value. When firstNameAtom or lastNameAtom changes, fullNameSelector recalculates, triggering re-rendering of the component.
Conclusion
By leveraging Recoil's selector, you can efficiently observe multiple atoms and derive new states based on their values. This approach enables flexible and performant handling of state sharing and updates across components.