react-lazily
TypeScript icon, indicating that this package has built-in type declarations

0.9.2 • Public • Published

react-lazily

minzip size install size dependency count

react-lazily is a simple wrapper around React.lazy (or loadable from @loadable/component) that supports named imports.

Usage

Consider a component MyComponent that is exported with a default export:

export default MyComponent;

Per React docs, you could use React.lazy as follows:

const MyComponent = React.lazy(() => import('./MyComponent'));

However, if the component is exported with a named export:

export const MyComponent = ...

You would have to use React.lazy like this:

But if the component is exported with named export export const MyComponent = ... then you have to do:

const MyComponent = React.lazy(() =>
  import('./MyComponent').then((module) => ({ default: module.MyComponent }))
);

With react-lazily it becomes:

const { MyComponent } = lazily(() => import('./MyComponent'));

Full example

See the live example: https://codesandbox.io/s/react-lazily-example-p7hyj

import React, { Suspense } from 'react';
import { lazily } from 'react-lazily';

const { MyComponent } = lazily(() => import('./MyComponent'));

const App = () => {
  const [open, setOpen] = React.useReducer(() => true, false);

  return (
    <>
      {open ? (
        <Suspense fallback={<div>Loading...</div>}>
          <MyComponent />
        </Suspense>
      ) : (
        <button onClick={setOpen}>Load</button>
      )}
    </>
  );
};

Full Example with @loadable/component

Don't forget to install @loadable/component first.

import React from 'react';
import { loadable } from 'react-lazily/loadable';

const { MyComponent } = loadable(() => import('./MyComponent'), {
  fallback: <div>Loading...</div>,
});

const App = () => {
  const [open, setOpen] = React.useReducer(() => true, false);

  return (
    <>
      {open ? <MyComponent /> : <button onClick={setOpen}>Load</button>}
    </>
  );
};

Related

Package Sidebar

Install

npm i react-lazily

Weekly Downloads

21,099

Version

0.9.2

License

MIT

Unpacked Size

7.56 kB

Total Files

13

Last publish

Collaborators

  • jlarky