Importing React
When I first started writing React, I noticed the requirement of importing React in my JSX files:
import React from 'react';
This wasn’t too much of a leap for me, since I had already been importing Ember for years before:
import Ember from 'ember';
But then, I noticed that people were importing all of React’s exports as a namespace:
import * as React from 'react';
I initially thought this was a fancy new way of importing React that would allow Webpack to perform advanced operations like tree shaking. Unfortunately, this is not the case. The reality is that these are just two different ways to import React
into your file.
Why do we need to import React anyway?
You may have noticed that even though you need to import React
, you don’t actually use it anywhere in your file. Usually, it is bad practice to leave unused variables sitting around in a file and your linter should complain. This is not the case for React
, however, since JSX requires it to be in scope. Eventually though, you won’t have to import React
at all for your JSX to know what is going on. You’ll only have to import the parts of React that you actually need, like hooks, context, and types (😏). In fact, Ember has already dropped the requirement for importing Ember
as of Ember 2.16.
Which one should you use?
You should use:
import React from 'react';
This is the most flexible way to import React
. Although there is no technical difference between the two, there are benefits to using more flexible syntax.
If you do end up importing all of React’s exports into the React
namespace using import * as React from 'react'
, you won’t be able to use any more named imports in the file. This is because everything has already been exported - just into the React
namespace. Because of this, anytime you need to use an export from React, you'll have to namespace it under React
; i.e. React.useState()
. Not only is this unnecessarily cumbersome and verbose, there may be a day when we don't need to import React
at all. If this day comes, it will be much simpler to remove one line of code per file rather than many. If you are reading this and cringing at the thought of having to manually import each named export of React (import { useState } from 'react';
) then I would argue you have a different issue. Your code editor should be declaring this import for you automatically and even ordering the imports!
By importing React
intead of all of the exports into the React
namespace we'll have less messy looking code that will be easier to maintain in the future.