1

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>
}

1 Answer 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;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.