Alexandru Popa
Alexandru Popa

Reputation: 155

Import hooks into React Typescript

I am trying to implement hooks into a React (^16.6.0) application using TypeScript

import * as React, {useState}  from 'react';

Any idea what is the right syntax for this import?

Upvotes: 12

Views: 20651

Answers (3)

mahdi komaiha
mahdi komaiha

Reputation: 141

Restarting Ts Server Helped in my case enter image description here

Upvotes: 5

ratbeard
ratbeard

Reputation: 307

I had the same error on "@types/react": "^16.8.17". Looking at it's type def file, it was missing the useState function for some reason, though it was mentioned in the comments of other hooks like useReducer.

Upgrading to "@types/react": "^16.8.18" with npm i @types/react@latest fixed it.

Upvotes: 12

Estus Flask
Estus Flask

Reputation: 222309

import supports a limited set of syntax variations.

It can be:

import React, {useState}  from 'react';

The downside is that entire library is imported, because React is default export and cannot be tree-shaken. Since the presence of React import is needed to use JSX syntax, a more efficient way is:

import * as React from 'react';
import {useState}  from 'react';

Hooks were introduced in pre-release React 16.7. react version constraint should be ^16.7.0-alpha.0, @types/react should be ^16.7.0.

Upvotes: 14

Related Questions