How to type the setState function from the useState hook
- Published on
- Ilkin Mammadov--2 min read
Imagine you have a component with a number state, and you pass the same state into another component for it you be used:
What should the SnippetsProps interface look like?
Most people will type something like this:
But it bothers me to have to import Dispatch
and SetStateAction
from react just to be able to define the interface.
The type Dispatch<SetStateAction<T>>
here is basically a function that accepts whatever type you declared your state is, in this case, its a number.
So basically you can also do this here:
We just saved two imports just by declaring it as a function that accepts a number, and returns nothing.
I know its just a small detail but I really believe it makes the code look cleaner.
This is just one of my pet peeves, but at the end of the day, it really depends on the coding standard that you or your company follows.
Hope you like one of my first blogs, will try to make more soon!