I am lazy loading a component based on two ids that sit in the Context.
const LazyStuff = () => {
console.log('---LazyStuff---');
//this is the module (which is quite a complex object managed with useReducer)
const {
isLoading: isLoadingModule,
isError: isErrorModule,
...module
} = useModuleContext();
//this is a callback that sets the module in the context based on some URL parameters
const setModuleByLocation = useSetModuleByLocation(module.dispatch);
useEffect(() => {
console.log('---useEffect---');
setModuleByLocation();
}, [setModuleByLocation]);
const Module = useMemo(
() =>
lazy(() =>
import(`@modules/${module.id}/${module.mode.id}`).catch(() => ({
default: () => null,
}))
),
[module.id, module.mode.id]
);
return (
<Suspense fallback={<>Loading...</>}>
<Module {...module} />
</Suspense>
);
};
export const ModuleProvider = ({ children }) => {
const reducer = (state, action) => {
switch (action.type) {
case 'SET_MODULE':
console.log('---SET_MODULE---');
return {
...state,
...action.payload
};
default:
return state;
}
};
const [state, dispatch] = useReducer(reducer, {
id: null,
mode: {
id: null
}
})
}
When I check the console, I see odd things:
- ‘—useEffect—‘ is logged once as expected
- ‘—LazyStuff—‘ is logged around 100 times (why???)
- ‘—SET_MODULE—‘ is logged around 100 times (why???)
I do not understand why there are so many rerenders of the component LazyStuff and especially, why —SET_MODULE— is executed so many times when the useEffect that does the dispatch only runs once…