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.
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>>) {}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With