Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add type notation to `React.useState`?

I am using React 16.8.3 with hooks, currently I want to type React.useState

type Mode = 'confirm' | 'deny'  
type Option = Number | null

const [mode, setMode] = React.useState('confirm')
const [option, setOption] = React.useState(100)

With my current code, mode is of type string, when instead I want it of type Mode. Same issue with Option.

How to add type notation to React.useState?

like image 510
Radex Avatar asked Mar 05 '19 10:03

Radex


People also ask

How do you add type to useState?

To type the useState hook as an object in React, use the hook's generic, e.g. const [employee, setEmployee] = useState<{name: string; salary: number}>({name: '',salary: 0}) . The state variable will only accept key-value pairs of the specified type. Copied!

Can we use TypeScript in React?

TypeScript is a language which extends JavaScript by adding type definitions, much like Flow. While React Native is built in Flow, it supports both TypeScript and Flow by default.

Does React Hooks work with static typing?

Do Hooks work with static typing? Hooks were designed with static typing in mind. Because they're functions, they are easier to type correctly than patterns like higher-order components. The latest Flow and TypeScript React definitions include support for React Hooks.

What type does useState return?

When we declare a state variable with useState , it returns a pair — an array with two items. The first item is the current value, and the second is a function that lets us update it.


1 Answers

React.useState uses a generic, so you can add type notation to it in this in this way:

const [mode, setMode] = React.useState<Mode>('confirm')
const [option, setOption] = React.useState<Option>(100)

Just for information ... type definition of React.useState:

function useState<S>(initialState: S | (() => S)): [S, Dispatch<SetStateAction<S>>];

like image 148
GibboK Avatar answered Oct 18 '22 09:10

GibboK