Snapshot object represents an immutable snapshot of the state of Recoil atoms. It is intended to standardize the API for observing, inspecting, and managing global Recoil state. It is mostly useful for dev tools, global state synchronization, history navigation, &c.
Snapshots are read-only with respect to atom state. They can be used to read atom state and evaluate selectors' derived state. The
getPromise() method can be used to wait for the evaluated value of asynchronous selectors, so you can see what the value would be based on the static atom state.
There are cases where you may wish to mutate a snapshot. While snapshots are immutable, they have methods to map themselves with a set of transformations to a new immutable snapshot. The map methods take a callback that is passed a MutableSnapshot, which is mutated throughout the callback and will ultimately become the new snapshot returned by the mapping operation.
reset() have the same signature as callbacks provided to a writeable selector's
set property, but they only effect the new snapshot, not the current state.
Recoil has the following hooks for working with snapshots:
useRecoilCallback()- Asynchronous access to snapshot
useRecoilSnapshot()- Synchronous access to snapshot
useRecoilTransactionObserver()- Subscribe to snapshots for all state changes
useGotoRecoilSnapshot()- Update current state to match snapshot
<RecoilRoot> component takes an
initializeState prop for initializing the global state via a
MutableSnapshot. This can be helpful for loading persisted state when you know all atoms in advance and is compatible with server-side rendering where the state should be setup synchronously with the initial render. For most state initialization and persistence, though, consider Atom Effects.