Skip to main content

useRecoilValueLoadable(state)

This hook is intended to be used for reading the value of asynchronous selectors. This hook will subscribe the component to the given state.

Unlike useRecoilValue(), this hook will not throw an Error or Promise when reading from an asynchronous selector (for the purpose of using React Suspense). Instead, this hook returns a Loadable object.

Use useRecoilValueLoadable_TRANSITION_SUPPORT_UNSTABLE() for experimental support for React 18 transitions based on mutating Recoil state.


function useRecoilValueLoadable<T>(state: RecoilValue<T>): Loadable<T>
  • state: an atom or selector that may have some asynchronous operations. The status of the returned loadable will depend on the status of the provided state selector.

Returns a Loadable for the current state with the interface:

  • state: indicates the status of the selector. Possible values are 'hasValue', 'hasError', 'loading'.
  • contents: The value represented by this Loadable. If the state is hasValue, it is the actual value, if the state is hasError it is the Error object that was thrown, and if the state is loading, then it is a Promise of the value.

Example​

function UserInfo({userID}) {
const userNameLoadable = useRecoilValueLoadable(userNameQuery(userID));
switch (userNameLoadable.state) {
case 'hasValue':
return <div>{userNameLoadable.contents}</div>;
case 'loading':
return <div>Loading...</div>;
case 'hasError':
throw userNameLoadable.contents;
}
}