By default most hooks infer types automatically, however here are some typing tips:
useState infers the type according to its initial state, if you don't define that state you can define the type manually, example:
The above statement will define that:
message
is of type string
.
setMessage
only accepts values of type string
or functions that return a string
.
useProp will not infer the type from the prop, you must define it, example:
Let's remember that useProp has a return api similar to useState, so the previous declaration will define that:
message
is of type string
.
setMessage
only accepts values of type string
or functions that return a string
.
both useMemo vs useCallback infer its type based on the callback that builds the memo state, but for certain conditions you may need to force the type return, example:
Although useMemo infers that its type is string, you can change the return rules via the first type parameter.
The above statement will define that:
message
is of type string
.
This applies equally to useCallback.
useEvent allows defining the detail structure through the type parameter, example:
The above statement will define that:
The dispatch callback expects an object of type {id: string}
as a parameter.
useRef allows to define through the type parameter the expected value of current in the reference.
The above statement defines:
refForm?.current
is of the type HTMLFormElement
.
useHost defines that current always exists, so the optional selector is not necessary, the type parameter of useHost allows to define the source Element, example:
All hooks in Atomico have Type declarations, explore them when importing each hook as a documentation source.