gregberge / loadable-components

The recommended Code Splitting library for React ✂️✨
https://loadable-components.com
MIT License
7.58k stars 376 forks source link

Add api exposing a hook-based way to load a module #976

Open edkimmel opened 10 months ago

edkimmel commented 10 months ago

Summary

Adds loadable.hook and lazy.hook as additional ways to load a dynamic module via @loadable

A common use case is to use some large third party library as part of a hook in first party code. By exposing a hook-based API in @loadable, it becomes trivial to dynamically load that library module.

const useThirdPartyAuthSdk = loadable.hook(() => 'some-large-sdk')
...

const useUserSignIn = () => {
  // 'some-large-sdk' is not loaded until this hook is ran
  const thirdPartyAuthSdk = useThirdPartyAuthSdk()
  const signin = React.useCallback(creds => {
    if (!thirdPartyAuthSdk) throw new Error('Auth SDK used before ready')
    thirdPartyAuthSdk.initiateSignin(creds)
  }, [thirdPartyAuthSdk])
  return {
    ready: !!thirdPartyAuthSdk,
    signin
  }
}

Test plan

loadableHook.test.js has been created mirroring loadable.test.js where applicable. An example for the hook api was created in the repository.

theKashey commented 10 months ago

Amazing job and quite interesting implementation. Big kudos for comprehensive tests.

However, let me be clear - I am going to add this PR to the list of all other things one way or another assigned to me and I cannot provide you any ETA for actual resolution. My presence in GitHub lands is quite limited nowadays.