Suspense-like Transitions In React – use-transition

Description:

Suspense like transitions without experimental react features today. For any fetching library.

It caches the previous result in case a transition occurs and only shows 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.

How to use it:

1. Install and import the hook.

# NPM
$ npm i @n1ru4l/react-use-transition
import * as React from "react";
import { unstable_batchedUpdates } from "react-dom";
import { createUseTransition } from "@n1ru4l/react-use-transition";
import { useQuery } from "your-fetching-library";

2. Basic usage.

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}
    </>
  );
};

Preview:

Suspense-like Transitions In React - use-transition

Add Comment