react-use-transition
Suspense like transitions without experimental react features today. For any fetching library.
Why?
Ever experienced flashy transitions where content disappears after triggering navigation, a loading state shows up for like 10 milliseconds, disappears and a new page is rendered? Did you wonder why it was even necessary to show a loading page in the first place?
That is exactly what this micro library tries to solve. Cache the previous result in case a transition occurs and only show some kind of loading indicator after a certain threshold (by default 300ms) has been reached without the new data arriving.
The concept is taken from the experimental React.useTransition
which is not stable as today and only available as an experimental build. This hook however works without React concurrent mode.
Use it together with your favorite GraphQL client such as relay
or urql
or any other data fetching library.
Install
yarn install -E @n1ru4l/react-use-transition
Usage
import * as React from "react";
import { unstable_batchedUpdates } from "react-dom"; // or react-native (your react reconciler)
import { createUseTransition } from "@n1ru4l/react-use-transition";
import { useQuery } from "your-fetching-library-of-choice";
const useTransition = createUseTransition(unstable_batchedUpdates);
const DataFetchingComponent = ({ postId }) => {
const { data, isLoading } = useQuery("/foo/:postId", { postId });
const [cachedData, showLoadingIndicator] = useTransition(data, isLoading);
return (
<>
{showLoadingIndicator ? <Spinner /> : null}
{cachedData ? (
cachedData.error ? (
<ErrorRenderer error={cachedData.error} />
) : (
<PostRenderer post={cachedData.post} />
)
) : null}
</>
);
};