Typing of React hooks in Typescript
Explain to me the setState. Hooks are now the better option to do effects in react. Using hooks with typescript can be complicated at first let’s dive in.
Inferring type
Typescript can infer types based on the parameters.
const [value, setValue] = useState(""); // const value: string
const [value, setValue] = useState(0); // const value: number
const [value, setValue] = useState(true); // const value: boolean// const setValue: Dispatch<SetStateAction<State>>
Providing type
Type can be provided by useHook<type>(arg)
syntax called Typescript Generics.
const [value, setValue] = useState<string>("");
// const value: stringconst [value, setValue] = useState<number>(0);
// const value: numberconst [value, setValue] = useState<boolean>(true);
// const value: boolean
Typescript Generics
Many of you can know generics from other languages such as C# or Java. The motivation for generics is to allow universal functions that can infer the type of the output based on input.
Let’s use a simplified useState hook type as an example.
function…