Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performance issue: Components library following the dot notation structure

I decided to follow the dot notation to create my components library like React-bootstrap does:

<Card>
  <Card.Body>
    <Card.Title>Card Title</Card.Title>
    <Card.Text>
      Some quick example text to build on the card title and make up the bulk of
      the card's content.
    </Card.Text>
  </Card.Body>
</Card>

To do it you need to graft the children components (like CardBody) to the 'main' component (here Card) just like that:

const Card = ({ children }) => <>{children}</>
const CardBody = () => <>Body</>

Card.Body = CardBody

export default Card

So that you can use all the children of Card very easily:

import Card from 'my-component-library/card'

<Card>
  <Card.Body>
  ...

This type of structure is used in a lot of components library but after reflection, I realize that with this structure, the import Card from 'my-component-library/card' is a significant action because under the hood there can be dozens of components that are imported and not used (like Card.Header or Card.Text).

So my question is: Is there a significant performance problem in this structure? Should I keep the default 'import useful component' structure like this?

import Card from 'my-component-library/card'
import CardBody from 'my-component-library/cardBody'

<Card>
  <CardBody>
  ...
like image 779
johannchopin Avatar asked Nov 06 '22 08:11

johannchopin


1 Answers

Very good question!

There are two points to discuss.

Point #1 - size and treeshaking.

When you are using

import {MyComponent} from './MyComponent'

Webpack (or other bundler) can shake the tree :) and take only that code you will really use.

In the case of

import * from 'MyLib'

You import everything (for your case as well). Usually, it's not a problem, but if you design the library - this is a really important point to take into consideration.

Point #2 - performance.

What happens when you importing the module?

  • Object allocated
  • javascript executed

What do I mean. Let's check this code:

some module

const MyComponent1 = (x) => `hello ${x}`;
const MyComponent2 = (y) => `good bye ${x}`

const data = Array.from(Array(1000)).fill(Date.now());
const MyComponent3 = () => `dates: ${data}.map((x, i)=> ...)`

When we importing this module, as far as it is in one file JS engine will: * create 3 new functions, * allocate 1 very big array.

This, of course, will need some time and memory. If we are going with a classic approach this will not a problem, because you split the code and move that to the separate files and related code will be executed only when you import them. In your approach - they will be executed in any case. For the library, this is also the important point.

That's actually it. Try both approaches, do some checks and pick an option that fits you the best.

like image 62
Drag13 Avatar answered Nov 15 '22 06:11

Drag13