typing hooks

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
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容