Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React: Importing modules with object destructuring, or individually?

In React, some packages allow you to import Components using either individual assignment: import Card from "@material-ui/core/Card", or via object destructuring: import { Card } from "@material-ui/core".

I read in a Blog that using the object destructuring syntax can have performance ramifications if your environment doesn't have proper tree-shaking functionality. The result being that every component of @material-ui/core is imported, not just the one you wanted.

In what situations could using object destructuring imports cause a decline in application performance and how serious would the impact be? Also, in an environment that does have all the bells and whistles, like the default create-react-app configuration, will using one over the other make any difference at all?

like image 700
Drowsy Avatar asked Oct 24 '25 11:10

Drowsy


1 Answers

Relying on package internal structure is often discouraged but it's officially valid in Material UI:

import Card from '@material-ui/core/Card';

In order to not depend on this and keep imports shorter, top-level exports can be used

import { Card } from "@material-ui/core"

Both are interchangeable, as long as the setup supports tree-shaking. In case unused top-level exports can be tree-shaken, the second option is preferable. Otherwise the the first option is preferable, it guarantees unused package imports to not be included into the bundle.

create-react-app uses Webpack configuration that supports tree-shaking and can benefit from the second option.

like image 74
Estus Flask Avatar answered Oct 27 '25 00:10

Estus Flask



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!