美文网首页
typing hooks

typing hooks

作者: Time_Notes | 来源:发表于2024-04-14 20:52 被阅读0次

    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

    相关文章

      网友评论

          本文标题:typing hooks

          本文链接:https://www.haomeiwen.com/subject/pvzcxjtx.html