Check the correct use of hooks
By default most hooks infer types automatically, however here are some typing tips:
useState
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 typestring
.setMessage
only accepts values of typestring
or functions that return astring
.
useProp
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 typestring
.setMessage
only accepts values of typestring
or functions that return astring
.
useMemo and useCallback
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 typestring
.
This applies equally to useCallback.
useEvent
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
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 typeHTMLFormElement
.
useHost
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.
Last updated