I am online
← Back to Articles

Here's how I use TypeScript with useState in React 👇

ReactjsJuly 29, 2024

Primitive Values

When dealing with data of type number, string, or boolean, it's perfectly fine to pass the default value and let TypeScript infer ("guess") the type.

Arrays and Objects

When you pass an empty array or object as the type though, TS can't possibly know what type of data will be stored in this variable.

It's good practice to tell TypeScript explicitly using generics what kind of data will be used by the React state when dealing with arrays and objects.

However, it's okay to let the type be inferred for primitives like strings and numbers.

// name: string
const [name, setName] = useState("");

// products: never[]
const [products, setProducts] = useState([]);

// products: Product[]
const [products, setProducts] = useState<Product[]>([]);

// product: {}
const [product, setProduct] = useState({});

// product: Product | null
const [product, setProduct] = useState<Product | null>(null);

Happy coding!