This API is currently under development and will change. Please stay tuned...
Recoil atoms represent local application state. Your application may have remote or server-side state as well, such as via a RESTful API. Consider synchronizing the remote state with Recoil atoms. Doing this allows you to easily access or write to the state from React components using the
useRecoilState() hook, or use that state as input to the Recoil data-flow graph for other derived state selectors. If you're looking to query a database or server for read-only data, consider using asynchronous selectors.
Local State Example
This example provides the friend status as local state only.
Sync State From Server
We can subscribe to asynchronous changes in the remote state and update the atom value to match. This can be done using standard React
useEffect() hook or other popular libraries.
If you want to handle synchronization of multiple atoms in a single place, you can also use the State Persistence pattern.
You can also sync the state so local changes are updated on the server. Note that this is a simplified example, please take care to avoid feedback loops.
Synching State with Parameters
You can also use the
atomFamily helper to sync local state based on parameters. Note that each call of this example hook will create a subscription, so take care to avoid redundant usage.
An advantage of using atoms to represent remote state is that you can use it as input for other derived state. The following example will show the current user and friend list based on the current server state. If the server changes the current user it will re-render the entire list, if it only changes the status of a friend then only that list entry will be re-rendered. If a list item is clicked on, it will change the current user locally and will update the server state.