ideas icon indicating copy to clipboard operation
ideas copied to clipboard

useLazyComponent

Open Tomekmularczyk opened this issue 5 years ago • 0 comments

I weren't sure whether this could go to the library but I was curious what others would think about it:

Description: It creates React.lazy component with custom Promise:

Basic usage:

const Person = ({ body }) => <p>{body.name}</p>;
const Failure = ({ status }) => <p>Failure, status code: {status}</p>;

function App({ id }) {
  const LazyPerson = useLazyComponent(
    () => request.get(`https://swapi.co/api/people/${id}`),
    Person,
    Failure
  );

  return (
    <Suspense fallback="...">
      <LazyPerson />
    </Suspense>
  );
}

By default, it would always return the same initially created LazyComponent - even when the arguments or props change - to avoid re-creating new components when re-render. However, this can be opt-in by passing the 4th argument:

const LazyPerson = useLazyComponent(
  () => request.get(`https://swapi.co/api/people/${id}`),
  Person,
  Failure,
  [`https://swapi.co/api/people/${id}`] // when this change I want a new LazyComponent
);

Any extra prop will be forwarded:

const Person = ({ extraProp }) => <p>{extraProp}</p>;

<Suspense fallback="...">
   <LazyPerson extraProp="something" />
</Suspense>

Here's an example https://codesandbox.io/s/8yoomy1xl9

Tomekmularczyk avatar Oct 28 '18 15:10 Tomekmularczyk