How to Add a Type to useState Setter Function in TypeScript

Published Feb 4, 2022  ∙  Updated May 2, 2022

How can we add a type to a useState() setter function in TypeScript?

Suppose we have an interface User.

interface User {
  id: number,

Let’s create a state using useState().

import React, { useState } from "react";
const [user, setUser] = useState<User>({id: 1});

How can we pass the setter function (i.e. setUser) into a function?

We would have to add the Dispatch type to that setter function.

import React, { Dispatch } from 'react';
const handler = (setter: Dispatch<User>) => {
  setter({ id: 2 });

We can then pass setUser into this handler() function.