React 18 - Infinite rendering when passing a state variable for lazy loading

Viewed 576

With react 17 via lazy loading, i was dynamically loading one of three components according to the selected language (state variable from zustand store). The import depends on that variable:

const MyComponent = lazy(() => import(`component-${language}.jsx`))

After migrating to react 18, the component is in infinite rendering.

I imagine it's related to the new automatic batching feature.

Somebody can help ? Best Regards

  • create a function outside the component to receive the variable as prop from the component or as direct import from the store but the error persists.

  • instead of the state variable i tried a getter from the store but with no success.

  • tried to use useState and useEffect replacing the state variable on the import but also with no success.

2 Answers

you can try this

<React.Suspense fallback="..."><MyComponent /></React.Suspense>

The infinite loading is due to the fact that import a statement under React.lazy triggers a rerender of the component. In my case I was calling the lazy function inside suspenses which triggered a infinite loop due to the lazy function causing a re render each time.

I fixed it by moving the import lazy call in the same component as Suspense.

Check the sandbox here

Related