5

I was wondering which of the two way of importing React named imports ( PropTypes , Component) in ES6 is the best.

First

import React, {PropTypes, Component} from 'react';

which would save a lot of typing specially on components that have lots of props to validate.

Second

import React form 'react';

and then calling them like React.Component when I want to use them.

Is there any performance difference between the two approaches or should I just pick whichever style I am more comfortable with ?

Community
  • 1
  • 1
Amir Hoseinian
  • 2,312
  • 2
  • 24
  • 27
  • 5
    *"should I just pick whichever style I am more comfortable with"* Yes. Any performance difference will be negligible compared to what the rest of your app is doing. – Felix Kling Feb 17 '17 at 07:33

2 Answers2

3

Whatever you prefer, but most importantly - stay consistent.


The community around React and the official docs prefer the second alternative, that's also my personal preference, because it is more descriptive.

import React from 'react';

and use it like

class Welcome extends React.Component { ... }
Chris
  • 57,622
  • 19
  • 111
  • 137
Lyubomir
  • 19,615
  • 6
  • 55
  • 69
2

I would say there is near-zero performance differences.

For me, the main advantages to the later is maintaining namespace: This is a contrived example, because you obviously wouldn't include lodash and underscore -

import { map } form 'lodash';
import { map } from 'underscore'; // oh no map-clash

vs

import lodash from 'lodash';
import underscore from 'underscore'; // lodash.map v underscore.map

However, I generally lean towards the destructured version (the {} version), because it "feels" tidier than these possibly big objects everywhere.

EDIT

One other thing worth noting, are more and more libraries are getting better at writing modules that can be imported as smaller parts of a larger whole - which works particularly well for ES6's import functionality.

For example, if you are only using map from lodash, importing like this:

import map from 'lodash/map';

instead of this:

import { map } from 'lodash';

will result in a much smaller final compiled file (if you have your browseifry/rollup/webpack/[insert flavour of the month] set up correctly) as it will only bring in the required code needed to execute map. Whereas the first one brings in all the things.

Chris
  • 54,599
  • 30
  • 149
  • 186