Home > Back-end >  React passing array subcomponent as a prop or importing it in each array item
React passing array subcomponent as a prop or importing it in each array item

Time:12-06

I have a component (ArrayComponent) that renders an array of data rows (RowComponents) that wraps the line inside a SubComponent. Is there any significant performance difference whether I import that impo on top level Component (ArrayComponent) and pass it as props to RowComponent component or import that SubComponent on each RowComponent? The array might have thousands of items in it.

Here is a very simplified example of both ways.

Having it imported in RowComponent would simplify few other things (not shown here) and I would prefer to use that.

CodePudding user response:

Assuming you use webpack or or a similar bundler (create-react-app gives you webpack out of the box) your code will be bundled into a single .js file and import statements are no longer relevant.

If this is the case, passing the subcomponent as a prop just adds complexity with no benefit.

CodePudding user response:

This is good example of props drilling. The reasonable solution to this would be using your own custom hooks. such as below;

const useMyArrayHook = () => {
 const myArray = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"];
 return myArray;
}

Now, rather passing this array into multiple components and sub-components, you can use in the target component where you want to use it, in your case in RowComponentWithImport.js and RowComponentWithoutImport.js components.

  • Related