React lazy

Created By: chatGPT

React provides a feature called React.lazy() that allows you to load components dynamically. This is particularly useful for optimizing performance in large applications by splitting your code into smaller chunks. With React.lazy(), you can load components only when they are needed.
const LazyComponent = React.lazy(() => import('./LazyComponent'));
To use React.lazy(), wrap it in a React.Suspense component. You can define a fallback UI, which will be displayed while the lazy component is being loaded.
<React.Suspense fallback={<div>Loading...</div>}>
    <LazyComponent />
</React.Suspense>
Ensure that you handle possible errors when using lazy loading. For this, you can use Error Boundaries in React.
class ErrorBoundary extends React.Component {
    constructor(props) {
        super(props);
        this.state = { hasError: false };
    }
    static getDerivedStateFromError(error) {
        return { hasError: true };
    }
    componentDidCatch(error, errorInfo) {
        console.log(error, errorInfo);
    }
    render() {
        if (this.state.hasError) {
            return <h1>Something went wrong.</h1>;
        }
        return this.props.children;
    }
}
You can use ErrorBoundary around your Suspense component to catch loading errors from your lazy-loaded components.
<ErrorBoundary>
    <React.Suspense fallback={<div>Loading...</div>}>
        <LazyComponent />
    </React.Suspense>
</ErrorBoundary>
In combination with React.lazy(), it's important to note that you cannot use this feature conditionally. This means that you cannot call React.lazy() inside conditionals or loops. Always declare your lazy-loaded components at the top level of your module.
// Don't do this!
if (someCondition) {
    const LazyComponent = React.lazy(() => import('./LazyComponent'));
}
Introduction And SetupComponentsPropsStateLifecycle MethodsHooksContext APIJsx SyntaxVirtual DomEvent HandlingFormsRoutingPerformance OptimizationError BoundariesHigher Order ComponentsRender PropsPortalsFragmentsRefsControlled ComponentsUncontrolled ComponentsMemoizationSuspenseLazy LoadingProp TypesDefault PropsConditional RenderingList And KeysAccessibility (a11y)State ManagementTestingCustom HooksUseEffectUseStateUseContextUseReducerUseMemoUseCallbackUseRefUseLayoutEffectUseImperativeHandleUseDebugValueAutomatic BatchingSuspense For Data FetchingStrict ModeForward RefsCreateContextLazyUseTransitionUseDeferredValueUseId