1.3.0 • Published 4 years ago

react-lazy-mount v1.3.0

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

react-lazy-mount

Lazily mount react components to render after an initial condition is met.

NPM JavaScript Style Guide Build Status

Install

npm install --save react-lazy-mount
or 
yarn add react-lazy-mount

Idea

Sometimes you don't want to load something until an initial condition is met. If you have an expensive component that is making api calls, or is rendering lots of children, initial and frequent mounting can hinder performance. LazyMount can help improve performance by mounting components based on an initial condition. It's like lazy loading, but instead of waiting for an initial render to load the module, it is waiting for an initial truthy conditional in order to render JSX.

Simple Example

import React from 'react';
import LazyMount from 'react-lazy-mount';

export const Example = () => {
  const [state, setState] = useState(false);

  return (
    // once trigger prop becomes "true" for the first time, 
    // the children props are mounted and will stay mounted 
    // regardless of state changes.
    <LazyMount trigger={state} >
      <div >I'm mounted</div>
    </LazyMount>
  );
};

In the above example, <div >I'm mounted</div> is only rendered after the state becomes true for the first time. If the state becomes false, LazyMount will still render the children. It waits for the first true value of the trigger, and then mounts the children.

Coupled with lazy loading

import React from 'react';
import LazyMount from 'react-lazy-mount';
const MyComponent = React.lazy(() => import('./MyComponent'));

export const Example = () => {
  const [state, setState] = useState(false);

  return (
    // once trigger prop becomes "true" for the first time, 
    // mycomponent will be lazy loaded, then mounted
    <LazyMount trigger={state} >
      // I'm optional
      <Suspense fallback={...} >
        <MyComponent />
      </Suspense>
    </LazyMount>
  );
};

Lazy mounting can be coupled with lazy loading to wait for a condition to be met in order to both load the module and render the component.

PropsTypeDefault ValueDescription
triggerBooleanfalseTrigger that listens for the first truthy value to render the children prop
childrenReactNode[]Component(s) that will be mounted once the trigger becomes true for the first time, and stay mounted regardless of any future trigger changes.

License

MIT © BenBrewerBowman


This hook is created using create-react-hook.

1.3.0

4 years ago

1.1.4

4 years ago

1.1.2

4 years ago

1.0.2

5 years ago

1.0.1

5 years ago