redux-dynamic-modules icon indicating copy to clipboard operation
redux-dynamic-modules copied to clipboard

Lazy Loading Support

Open SantoJambit opened this issue 6 years ago • 0 comments

I am currently working on a presentation about react modularization and it contains both redux-dynamic-modules and React.lazy (for code-splitting). While doing this, I was wondering why modules are not lazy loaded, but I couldn't find any existing solutions.

So I started a proof-of-concept:

interface LazyDynamicModuleLoaderProps {
    imports: Array<() => Promise<{ default: () => IModule<any> }>>;
    loading: JSX.Element;
}

function LazyDynamicModuleLoader<T>({ imports, children, loading }: PropsWithChildren<LazyDynamicModuleLoaderProps>) {
    const [modules, setValue] = useState<Array<IModule<any>> | null>(null);
    useEffect(() => {
        Promise
            .all(imports.map((get) => get()))
            .then((result) => setValue(result.map((r) => r.default())));
            // fixme: catch and show error
    }, []);
    if (!modules) {
        return loading;
    }
    return <DynamicModuleLoader modules={modules}>{children}</DynamicModuleLoader>;
}

ReactDOM.render((
    <Provider store={store}>
        <LazyDynamicModuleLoader imports={[() => import('./redux/module')]} loading={<div>Loading..</div>}>
            <LazyApp />
        </LazyDynamicModuleLoader>
    </Provider>
), document.getElementById('app'));

It seems to work in my sample to-do app and I was wondering if anyone tried this before and if this is, for some reason, a bad idea. I guess it might not have much benefit for smaller applications, but in bigger applications, this could be worthwhile? Or it's just premature optimization.

If this is worthwhile, could this functionality be incorporated into redux-dynamic-modules? Should I create a PR?

SantoJambit avatar Jan 07 '20 10:01 SantoJambit