ReactuseContext 实际意义上并不是状态解决方案,它与状态管理没有任何关系,它是关于依赖注入的,向包装组件提供一个值,然后任何下游组件都可以通过 useContext 钩子使用这个值

创建一个钩子,用来快速创建和实现useContext

createStateContext

export function createStateContext<T>() {
 
  const StateContext = React.createContext<undefined | Readonly<[T, React.Dispatch<React.SetStateAction<T>>]>>(undefined);
 
  function useStateContext() {
    const tuple = useContext(StateContext)
    if (tuple === undefined) {
      throw new Error(
        `use${StateContext.displayName} must be used within a ${StateContext.displayName}Provider`,
      )
    }
    return tuple
  }
  return [StateContext, useStateContext] as const
}

Use

const [CheckboxContext, useCheckboxContext] = createStateContext<string[]>()
// optional for better error messages
CheckboxContext.displayName = "CheckboxContext"
function CheckboxGroup({ children }) {
  const state = useState<string[]>([])
  return (
	<CheckboxContext.Provider value={state}>
	  {children}
	</CheckboxContext.Provider>
  )
}