use-lazy-component
TypeScript icon, indicating that this package has built-in type declarations

1.0.0 • Public • Published

npm npm

Simple react hook to lazily load a component

  • Can be used as a very simplistic alternative to React.Suspense

Installation

npm i -s use-lazy-component

Or

yarn add use-lazy-component

Usage

Basic usage

import useLazyComponent from 'use-lazy-component';
const SomeComponent = () => {
  const { component: Component, loading, error } = useLazyComponent<BigComponent>(
    () => import('./bigComponent');
  );
 
  return (
    <div>
      {!loading && <Component/> }
    </div>
  )
}

Load different component depending on result of promise

import useLazyComponent from 'use-lazy-component';
const SomeComponent = () => {
  const { component: Component, loading, error } = useLazyComponent<BigComponent>(
    async () => {
      const result = await someAsyncFunction();
 
      if (result) {
        return import('./bigComponent');
      }
      return import('./defaultComponent');
    }
  );
 
  return (
    <div>
      {!loading && <Component/> }
    </div>
  )
}

Install

npm i use-lazy-component

DownloadsWeekly Downloads

2

Version

1.0.0

License

MIT

Unpacked Size

9.48 kB

Total Files

4

Last publish

Collaborators

  • tjbroodryk