Import React
vs Import React, { Component }
Which one is better and why?
Or does it make no difference other than writing less cod
TLDR;
it's entirely personal preference.
Just a note…
import React, { Component }
lets you doclass Menu extends Component
instead ofclass Menu extends React.Component
. It's less typing…
If you want to do less typing, then don't import Component in addition to React.
import React, { Component } from 'react';
class Menu from Component {
is more typing than:
import React form 'react';
class Menu from React.Component {
even if you consider auto-completion. ;)
What these are are named imports or namespace imports. What they do is basically copy over the module's contents into the namespace allowing:
import React, { Component } from 'react';
class SomeComponent extends Component { ... }
Normally, we'd extend React.Component
, but since the Component module is imported into the namespace, we can just reference it with Component
, React.
is not needed. All React modules are imported, but the modules inside the curly brackets are imported in such a way that the React
namespace prefix is not needed when accessing.
import React, { Component }
lets you do class Menu extends Component
instead of class Menu extends React.Component
. It's less typing and duplication of the React namespace, which is generally a desired modern coding convention.
Additionally, tools like Webpack 2 and Rollup do "tree shaking," meaning any unused exports are not bundled into your final code. With import React
/React.Component
you are guaranteeing all of React's source code will be bundled. With import { Component }
, some tools will only bundle the code needed to use the Component
class, excluding the rest of React.
The above paragraph is irrelevant in this specific case, because you always need to have React in the current namespace to write JSX, but only importing the exact modules you need in other cases may lead to smaller bundled code in the end.
Beyond that it's entirely personal preference.