Correctly typing React Hooks?

Viewed 55

What is the correct (or at least idiomatic) way to type a state hook in TypeScript?

Is it

const [items, setItems] = useState( [] as SomeType[] )

or

const [items, setItems] = useState<SomeType[]>( []  )

or something else? Or are there really no meaningful differences among the options?

1 Answers

The main diff between those is that typescript is pulling the type from the value rather than you giving it directly to the useState hook.

There's no correct way of doing it, but it might be more readable if you stick to option two..

An example where it gives a reason to stick with option two is for example when you initialize the state value by giving it a function

const [items, setItems] = useState<SomeType[]>(() => someExpensiveWayOfGettingTheValue...);

Another reason to stick with option two is when you're not wanting to provide an initialValue

const [value, setValue] = useState<Sometype>();
Related