Import hooks into React Typescript
Asked Answered
S

4

12

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?

Satiate answered 21/11, 2018 at 14:29 Comment(0)
S
14

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.

Slosberg answered 21/11, 2018 at 14:55 Comment(2)
Sorry still not working it gives me the following 'Module '"C:/web-client-ts/node_modules/@types/react/index"' has no exported member 'useState'.'Satiate
It should be because of the version in "@types/react" is not yet updated. Please npm i @types/react@latest and try againLlama
K
12

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.

Krueger answered 28/5, 2019 at 15:17 Comment(2)
still giving the errorLocust
Also bugged in the 17.x.x branch. 17.0.27 bugged, 17.0.44 fixed.Malefic
A
5

Restarting Ts Server Helped in my case enter image description here

Augustusaugy answered 16/11, 2023 at 15:2 Comment(0)
A
0

try installing npm i @types/react

Arboretum answered 11/8, 2023 at 18:4 Comment(1)
Suggesting to install @types/react already covered here: stackoverflow.com/a/56345351Hunsaker

© 2022 - 2024 — McMap. All rights reserved.