typing hooks

2024-04-14  本文已影响0人  Time_Notes

useState: simple state values

type inference take care of simple values

when initial value is only know at a future point in time

useState<User | null> optional chaining operator

this is because use can be null, so only if user exists, access the name property

always check before accessing the property


use type assertion to let ts know that user is always of type User and won't be null

{} as AuthUser

this can allow us to access name without a check


useReducer: for complex state logic, for example next state depends on previous state

reducer(state, action)

strict type with string literals

discriminate unions if using optional mark for action, action.payload needs checking

use context: to consume the context value

1. context already knew

create/export context and a component that provide context value  invoke context provider with box as children consume context in children

2. context is a future value

provide the user and the function to set user when they log in or log out

can use type assertion AS or null (with optional chaining ?) future value being set in a component

useRef senarios:

1. as a read-only ref for dom element

reference to HTMLInputElement

use type assertion ! if you know it is not null when accessing it to avoid optional chaining ?

2. as a mutable value which can behave like an instance variable

as a mutable value
上一篇下一篇

猜你喜欢

热点阅读