'how to handle lazy import in functional component react js avoid import befor need to render

Get data from multiple form it causes load more and become slow. How to avoid import or run code before render the element.

Here the below code run both element . ProductTitle and ProductDemo style is "none" but it consol.log("ProductTitle") and consol.log("ProductDemo") are executed.

Main js

import { lazy } from 'react';
const ProductTitle = lazy(() => import('./ProductTitle'))
const ProductDemo = lazy(() => import('./ProductDemo'))
import { useState } from 'react';
import { Panel } from 'react-instantsearch-dom';


const Product = () => {
    const [panel, SetPanel] = useState(0)
    
    return (<div>
        
         <button onClick={()=>SetPanel(panel +1)} >Next panel</button>
       <Suspense fallback={null}  >
        <div style={{ display: (panel === 1) ? 'none' : 'block' }} >
            <ProductTitle />
        </div>
        <div style={{ display: (panel === 2) ? 'none' : 'block' }} >
            <ProductDemo />
        </div>
    </Suspense>
    
    </div>);
}

export default Product;

ProductTitle.js

const ProductTitleA = ({ }) => {
    console.log("ProductTitle")
    
    return <div>
        this ProductTitle Panel
    </div>
}

ProductDemo.js

const ProductDemo = ({ }) => {
    console.log("ProductDemo")

    return <div>
        this ProductDemo Panel
    </div>
}


Solution 1:[1]

You can prevent those children components from mounting by doing this:

import { lazy } from 'react';
const ProductTitle = lazy(() => import('./ProductTitle'))
const ProductDemo = lazy(() => import('./ProductDemo'))
import { useState } from 'react';
import { Panel } from 'react-instantsearch-dom';


const Product = () => {
    const [panel, SetPanel] = useState(0)
    
    return (<div>
        
         <button onClick={()=>SetPanel(panel +1)} >Next panel</button>
       <Suspense fallback={null}  >
        {(panel === 1) ? <div/> : <div >
            <ProductTitle />
        </div>}
        {(panel === 2) ? <div/> : <div>
            <ProductDemo />
        </div>}
    </Suspense>
    
    </div>);
}

export default Product;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ingenious_Hans