npm.io
1.0.0 • Published 6 years ago

use-lazy-component

Licence
MIT
Version
1.0.0
Deps
0
Size
9 kB
Vulns
0
Weekly
0

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

Keywords