Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 802
priyanshu sinha Avatar asked Dec 11 '25 17:12

priyanshu sinha


1 Answers

You could create a Higher Order Component that fetches the hook and then passes it down as a prop to a wrapped component. By doing so the wrapped component can use the hook without breaking the rules of hooks, eg from the wrapped component's point of view, the reference to the hook never changes and the hook gets called everytime the wrapped component renders. Here is what the code would look like:

export function withDynamicHook(hookName, importFunc, Component) {
    return (props) => {
        const [hook, setHook] = useState();

        useEffect(() => {
            importFunc().then((mod) => setHook(() => mod[hookName]));
        }, []);

        if (!hook) {
            return null;
        }

        const newProps = { ...props, [hookName]: hook };
        return <Component {...newProps} />;
    };
}

// example of a Component using it:
const MyComponent = ({useMyHook}) => {
    let something = useMyHook();
    console.log(something)
    return <div>myHook returned something, see the console to inspect it </div>
}
const MyComponentWithHook = withDynamicHook('useMyHook', () => import('module-containing-usemyhook'), MyComponent)


like image 82
user3692823 Avatar answered Dec 13 '25 07:12

user3692823



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!