user5183133
user5183133

Reputation:

Import React vs React, { Component }

Import React vs Import React, { Component }

Which one is better and why?

Or does it make no difference other than writing less code later on?

Does writing { Component } mean it only imports the Component object?

Upvotes: 17

Views: 12307

Answers (3)

John Albin Wilkins
John Albin Wilkins

Reputation: 130

TLDR;

it's entirely personal preference.

Just a note…

import React, { Component } lets you do class Menu extends Component instead of class 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. ;)

Upvotes: 3

Andy Ray
Andy Ray

Reputation: 32076

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.

Upvotes: 25

Andrew Li
Andrew Li

Reputation: 58002

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.

Upvotes: 5

Related Questions