microsoft / redux-dynamic-modules

Modularize Redux by dynamically loading reducers and middlewares.
https://redux-dynamic-modules.js.org
MIT License
1.07k stars 116 forks source link

Lazy Loading Support #125

Open SantoJambit opened 4 years ago

SantoJambit commented 4 years ago

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?