1.0.0 • Published 4 years ago

use-lazy-component v1.0.0

Weekly downloads
3
License
MIT
Repository
github
Last release
4 years ago

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