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
?
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!
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.
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.
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.
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>>];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With