What is the type of the useState setter function?

Viewed 98

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.

1 Answers

The type of the state setter is like this:

React.Dispatch<React.SetStateAction<TypeOfTheState>>

For this one:

const [infoText, setInfoText] = useState<string>(""); 

setInfoText is of type:

React.Dispatch<React.SetStateAction<string>>
Related