Home > database >  React/TypeScript - What does "Dispatch<SetStateAction<boolean>>" stand for?
React/TypeScript - What does "Dispatch<SetStateAction<boolean>>" stand for?

Time:03-03

I am writing Frontend Tests for React Components in TypeScript. Since the Code is from a more experienced Programmer, some Datatypes seem a bit new for me. Now I've got a prop that is defined with "Dispatch<SetStateAction>" as datatype. I've noticed that using the set-property of a useState-Hook is working, but I'm not really sure if this is how the prop is supposed to be used. For reference: The prop is called "onFullScreenClick". I'd be very grateful for an explanation and an example for what's most likely to be put in

CodePudding user response:

If you look at the source of the typings:

type SetStateAction<S> = S | (prevState: S) => S;

type Dispatch<A> = (action: A) => void;

Dispatch takes an action as a parameter and returns nothing. There are multiple types of actions, and one of them is SetStateAction.

Remember that useState can take a new state, or a function that takes the previous state and returns the new state.

So useState's type is actually:

type UseState<S> = (action: S | ((prevState: S) => S)) => void;

CodePudding user response:

It's just a way telling typescript, the type of the props we are passing in

Take a look at this simply counter example from sandbox

We have const [num, setnum] = useState(0) in the parent, and we pass both state and setter function to child component

The type of the num is infered from useState(0), if we want the type of the setter function, we just hover mouse over it, and we get

const setNum: Dispatch<SetStateAction<number>>

and this Dispatch<SetStateAction<number>> is the type of setter function.

  • Related