Search code examples
javascriptreactjsreact-hooksdynamic-import

Dynamic import of react hooks


Can we dynamically import hooks based on the value passed to the component?

For eg.

App.js

<BaseComponent isActive />

BaseComponent.js

if(props.isActive) {
  // import useActive (custom Hook)
}

I donot want these(custom hook) files to be imported and increase the size of BaseComponent even when the props contain falsey values.


Solution

  • You can dynamically import hooks as it is just a function (using require), but you shouldn't because you can't use hooks inside conditions.

    See Rules of Hooks

    Only call Hooks at the top level. Don’t call Hooks inside loops, conditions, or nested functions.

    If you want conditionally use a hook, use the condition in its implementation (look for example at skip option of useQuery hook from Apollo GraphQL Client).

    const useActive = (isUsed) => {
      if (isUsed) {
        // logic
      }
    }