Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
196 views
in Technique[技术] by (71.8m points)

javascript - Difference between importing module and passing it as a prop vs importing it from within the module that actually uses it

Consider this first approach. It imports SomeMassiveModule in the Parent component and then passes it down to the Child components.

// Parent.js
import React from 'react'
import * as SomeMassiveModule from 'some-massive-module'

export default function Parent() {
    return (
        <Child SomeMassiveModule={SomeMassiveModule} />
        <Child SomeMassiveModule={SomeMassiveModule} />
        <Child SomeMassiveModule={SomeMassiveModule} />
    )
}
// Child.js
import React from 'react'

export default function Child({ SomeMassiveModule }) {
    return (
        <div>
            {SomeMassiveModule.SomeComponent}
        </div>
    )
}

Now, consider this second approach, which imports SomeMassiveModule in the Child component and then uses it.

// Parent.js
import React from 'react'

export default function Parent() {
    return (
        <Child />
        <Child />
        <Child />
    )
}
// Child.js
import React from 'react'
import * as SomeMassiveModule from 'some-massive-module'

export default function Child() {
    return (
        <div>
            {SomeMassiveModule.SomeComponent}
        </div>
    )
}

Is there a difference in performance between these two approaches? Does the bundling now happen three times in the second approach instead of just the once?

question from:https://stackoverflow.com/questions/65933342/difference-between-importing-module-and-passing-it-as-a-prop-vs-importing-it-fro

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use the first approach when you want to pass different values in the props to the Child component. If it is going to be the constant (won't change in future) import option i.e 2nd approach seems better than the first one.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...