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

State and reducers are not removed when dynamic component unmounts #167

Open madrussa opened 3 years ago

madrussa commented 3 years ago

When mounting a module using the DynamicModuleLoader and then later unmounting it, the state and reducers remain.

This can be verified by removing a DynamicModuleLoader and inspecting Redux using redux dev tools. The state applied when the module was loaded remains after the component is removed.

I have a solution but this took a while to work out what was going on, storing here for those who come across this same issue. The fix would be to document this feature.

Solution: There is an undocumented strictMode property you can add to the loader. If you are using strict mode you must add this to all of your dynamic modules.

<DynamicModuleLoader key="myModule" modules={[getMyModule()]} strictMode>
    <MyComponent />
</DynamicModuleLoader>

https://github.com/microsoft/redux-dynamic-modules/blob/c1439e67de12488a142df9c07cbc394e87e329cf/packages/redux-dynamic-modules-react/src/DynamicModuleLoader.tsx#L15-L21

As shown above, what happens if you do not include the flag is the module manager will add the module twice, but only removes it once. This has the side effect of causing the reference counter to always think the module is still required.

luox12 commented 3 years ago

thanks @madrussa for your resolution.

Pabliomen commented 2 years ago

Thanks @madrussa this really helped me! works like a charm