• Что бы вступить в ряды "Принятый кодер" Вам нужно:
    Написать 10 полезных сообщений или тем и Получить 10 симпатий.
    Для того кто не хочет терять время,может пожертвовать средства для поддержки сервеса, и вступить в ряды VIP на месяц, дополнительная информация в лс.

  • Пользаватели которые будут спамить, уходят в бан без предупреждения. Спам сообщения определяется администрацией и модератором.

  • Гость, Что бы Вы хотели увидеть на нашем Форуме? Изложить свои идеи и пожелания по улучшению форума Вы можете поделиться с нами здесь. ----> Перейдите сюда
  • Все пользователи не прошедшие проверку электронной почты будут заблокированы. Все вопросы с разблокировкой обращайтесь по адресу электронной почте : info@guardianelinks.com . Не пришло сообщение о проверке или о сбросе также сообщите нам.

Do You Still Need to Import React in `.tsx` Files?

Lomanu4 Оффлайн

Lomanu4

Команда форума
Администратор
Регистрация
1 Мар 2015
Сообщения
1,481
Баллы
155

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.



Do You Still Need to Import React in .tsx Files?


If you're working with modern React and seeing something like:

React is declared but its value is never read
You’re not alone. This post clarifies when you actually need to import React, and why this warning often isn’t an error at all.

The Myth: "You must always import React"


In older versions of React (pre-17), importing React was essential:


import React from 'react';

That’s because JSX was transpiled into React.createElement() calls under the hood.

However, with React 17+ and the introduction of the new JSX transform, this is no longer required.

The Modern JSX Transform


React 17+ and TypeScript 4.1+ introduced a new way to compile JSX:


// tsconfig.json
{
"compilerOptions": {
"jsx": "react-jsx"
}
}

With this setting, JSX is compiled without requiring React in scope. So this:


const Hello = () => <h1>Hello</h1>;

Does not need:


import React from 'react';

And that’s why you're seeing the warning—you’ve imported React, but you're not actually using it. TypeScript is just letting you know.

What Should You Do?

✅ Option 1: Remove the Unused Import


Simply delete the unused import React from 'react'.


// ❌ Not needed
// import React from 'react';

// ✅ Modern React
const MyComponent = () => <div>Hello Modern React</div>;
✅ Option 2: Suppress the Warning (Not Recommended)


You can suppress unused imports, but this is not ideal in long-term codebases.

Real Example: TypeScript + React Setup


Here's a typical tsconfig.json for React 17+:


{
"compilerOptions": {
"jsx": "react-jsx",
"strict": true,
"esModuleInterop": true,
...
},
"include": ["src"]
}

As long as jsx: react-jsx is configured, you're good to go.

Common Misunderstanding

"But my project compiles fine—why the warning?"
✅ Because the JSX is valid, but the React import isn’t used anymore.

? So clean up the import to silence the warning and embrace modern React.

Developer Insight


This change reflects React’s broader move toward simplicity and improved DX (developer experience):

  • Less boilerplate in every file
  • Easier onboarding for new developers
  • Fewer things to "just remember" to include
TL;DR

SituationShould you import React?
Pre-React 17✅ Yes, always
React 17+ with react-jsx compiler❌ No, not required
Seeing React is declared but unused ✅ Remove it
Conclusion


Modern React doesn’t need import React in every component. If you’re getting a “React is declared but never read” warning—it’s because your tools are smarter now.

Clean code is happy code. Remove unused React imports, configure your compiler correctly, and enjoy writing leaner, faster React apps.

Tags: react typescript eslint frontend jsx webdev


Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

 
Вверх Снизу