In a course I'm doing on TS, they introduce this definition for useState generics but it was skimmed over and I'd like to understand better
function useState<S>(initialState: S | (() => S)):
[S, Dispatch<SetStateAction<S>>];
from my understanding after reading many things about this, I follow most of it but am lost by the Dispatch<SetStateAction<S>>
part, I see that the type is passed into SetStateAction but not sure how its working and what goes to Dispatch, would like a good explanation of this please.
Dispatch
is a type which the react library has defined. That type's definition is:
type Dispatch<A> = (value: A) => void;
Ie, a function that takes in some value, and returns nothing. Consequently this:
Dispatch<SetStateAction<S>>
... is the same as:
(value: SetStateAction<S>) => void;
That prompts us to find out what SetStateAction is, and it's this:
type SetStateAction<S> = S | ((prevState: S) => S);
Ie, it's either a value, or a function that receives the previous value and returns a new one
So putting it all together, Dispatch<SetStateAction<S>>
is the same as:
(value: S | ((prevState: S) => S)) => void;
In other words, it's a function that you can either pass a new value into, or you can pass an update function into it.
eg:
const [name, setName] = useState<string>('alice'); // <string> is optional, because typescript can figure it out from context
// Can either pass in a string
setName('bob');
// or a function that both receives and returns a string.
setName((prev: string) => {
return prev + ', the almighty';
});