loadable-components icon indicating copy to clipboard operation
loadable-components copied to clipboard

How to lazyload a hook?

Open ion-willo opened this issue 1 year ago • 3 comments

💬 Questions and Help

I have a module that exports both a React Component and a hook to configure the component.

I tried:

const Carousel  = loadable(() => import('../components/ui/Carousel'), {
  resolveComponent: (components) => components.Carousel
})
const useCarousel  = loadable.lib(() => import('../components/ui/Carousel'), {
  resolveComponent: (components) => components.useCarousel
})

But this failed the first time I tried calling useCarousel saying that useCarousel is not a function.

Any help would be appreciated.

ion-willo avatar Jul 20 '23 15:07 ion-willo

Look like a little gap in documentation. The result of any operation is a component. loadable.lib is render prop pattern giving you access to any function "dynamically". Stil you cannot use it as you might want.

const Carousel  = loadable.lib(() => import('../components/ui/Carousel'));
//...
<Carousel>{({useCarousel}) => useCarousel()....}</Carousel>

If only loadable.lib had a hook form 😭

theKashey avatar Jul 21 '23 07:07 theKashey

Damn, that's a pity...

Is there a feature request I can vote on for implementing this?

ion-willo avatar Jul 21 '23 07:07 ion-willo

This library is not really under active development and frankly speaking even not under very active maintenance. So unless someone steps in to implement a few feature it will be not implemented.

At the same time this feature is "supported" by react-imported-component "supported" because you our will get fancy API and waterfall requests, or not fancy code you might have to "micromanage". There is no preexisting example for "hooks", let me provide one here

const MyComponent = () => {
  // you can import whatever you want
  const {
      imported: useCarousel,
      loadable: carouselLoadable
    } = useImported(() => import('../components/ui/Carousel'),(components) => components.useCarousel );

   // but in order to "obey" the rule of hooks you need to "break" this component
   if(!useCarousel){
     throw carouselLoadable.resolution;
   }
   // you can combine `useImported` and `throw` in a custom hook, but that would cause waterfalls
}

theKashey avatar Jul 22 '23 01:07 theKashey