Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the type of the useState setter function?

Sometimes the setter function of a useState hook must be passed around. What is the right way to type that function?

// some component with useState
const [infoText, setInfoText] = useState<string>(""); 

// same component calls a function in which the setter function is needed.
getInfoText(setInfoText);

// in the definition of that function (getInfoText) I now want to correctly type the setter function
export function getInfoText(setInfoText: ???) {

P.S.: I know that there are a couple of similar questions. I want to provide a general question without context such as: what is the correct type for this piece of code.

like image 732
Flip Avatar asked Oct 18 '25 17:10

Flip


1 Answers

The type of the state setter in React is Dispatch<SetStateAction<TypeOfTheState>> where Dispatch, and SetStateAction can be imported from "react". As an example:

import { Dispatch, SetStateAction, useState } from "react";

export default function Component() {
  // The type of setInfoText is Dispatch<SetStateAction<string>>
  const [infoText, setInfoText] = useState<string>("");

  // We can give it as an argument to foo, as it's typed below
  foo(setInfoText);

  return <></>;
}

function foo(stateSetter: Dispatch<SetStateAction<string>>) {}
like image 137
yousoumar Avatar answered Oct 20 '25 06:10

yousoumar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!