← Go Back

You don't always need to import React

Broken Post?Let me know

r/reactjs has a Weekend Reads, which is a "'book club' type thing where we read something every weekend".

Last week's topic was JSX In Depth, and I would like to share something that's been bothering me but learned why.

The question is "why do you import React" when "React" is not used anywhere in your component code?

🎶 Intro

When you start learning react, you might been told to always import React, import React from "React" in your component file.

But that's not always necessary.

To understand why, let's see what JSX is.

🤔 JSX?

The subtitle in JSX in Depth describes JSX as

Fundamentally, JSX just provides syntactic sugar for the React.createElement(component, props, ...children) function

You can either use the JSX syntatic sugar 🍬 to create components or use React.createElement directly if you are not transpiling your source code.

🙄 Then shouldn't you import React everywhere?

No. not unless you use React object for your component.

You can create a "function" component that returns value(s) of a simple JavaScript primitives, such as string or number.

export default props => ["Not importing React is fine!", 1, 2, 3];
view raw App.js hosted with ❤ by GitHub

View this gist on GitHub

That is the full source for App.js.

In this case, React object is not used anywhere so you can leave out the import statement (but still is a valid component).

📒 Note: If you are creating a class component, you need to import React as it needs to extend _React.Component_.

And then you can import App.js just like any React component (Line #4).

import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
view raw Index.js hosted with ❤ by GitHub

View this gist on GitHub

👋 Parting Words

I hope this has solved for the need to import React for components.

99% of the time, you'd use React object in someway to create a component so probably a good idea to import React anyway.
☝ Forget about this ever written...😅

🏔 Resources