How to use TypeScript with React Hooks
My favourite thing about using TypeScript is that your code editor can catch type errors before you even run your code. And my favourite JavaScript framework is React, which as standard is for writing in normal JavaScript. That doesn't however mean we can't write React applications in TypeScript. We can! Which means we get the best of both worlds. I will write another longer article about how to use TypeScript with React because there is quite a lot to cover.
The first obstacle I find developers come across when writing TypeScript with React, is the ability to use React's useState hook. Or more specifically:
"how do you assign a type against React state when setting the default value using the useState hook?"
The answer is, like this. I have added multiple examples for some different types below:
String type
const [myString, setMyString] = useState<string>('default string');
Number type
const [myNumber, setMyNumber] = useState<number>(0);
Boolean type
const [myBool, setMyBool] = useState<boolean>(false);
Setting an array type using an interface:
interface myArrayInterface {
name: string;
age: number;
default: boolean;
}
const [myArray, setMyArray] = useState<myArrayInterface[]
>([]);