All Posts

Is it necessary to import React in each and every functional component?

Yojan Regmi on July 20 2024

When I first started learning React, each and every tutorials, videos and blog posts started writing React code by importing React first at the top of the file. As I learned further I grew curious what is the purpose of importing React in each and every file.

Understanding what JSX is transformed into.

Before React 17.0, suppose our code looks like this:

import React from 'react';

function App() {
  return <h1>Hello World</h1>;
}

The browser does not understand the JSX so it will throw an error. So compiler like Babel transforms it into regular javascript. The above code becomes:

import React from 'react';

function App() {
  return React.createElement('h1', null, 'Hello World');
}

Which means all the black magic we were doing like writing HTML inside a function is just transformed into a function call with arguments .So if we didn't import React in our component React.createElement would be undefined because React does not exist.

So this is before React 17.0, but what about after 17.0?

After React 17.0, instead of transforming JSX to React.createElement, compilers automatically import appropriate functions required and calls them.

But we still need to import React, if we are using hooks in our code.