How to Add a Type to useState Setter Function in TypeScript


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.

handler(setUser)