All files / react useToggle.ts

100% Statements 11/11
100% Branches 0/0
100% Functions 6/6
100% Lines 10/10

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47                                                              10x 10x 1x   10x 3x   10x 1x   10x 1x   10x    
import { useCallback, useState } from 'react'
 
/**
 * @public
 */
export type UseToggleResult = [
  boolean,
  {
    (): void
    set(value: boolean): void
    true(): void
    false(): void
  },
]
 
/**
 * 布尔值切换器。
 *
 * @public
 * @param initialValue 初始值
 * @returns 返回结果和操作
 * @example
 * ```typescript
 * const [value, toggle] = useToggle(false) // value: false
 * toggle() // value: true
 * toggle.set(false) // value: false
 * toggle.true() // => value: true
 * toggle.false() // => value: false
 * ```
 */
export function useToggle(initialValue: boolean): UseToggleResult {
  const [value, setValue] = useState(initialValue)
  const toggle = (useCallback(() => {
    setValue(value => !value)
  }, []) as any) as UseToggleResult[1]
  toggle.set = useCallback(value => {
    setValue(value)
  }, [])
  toggle.true = useCallback(() => {
    setValue(true)
  }, [])
  toggle.false = useCallback(() => {
    setValue(false)
  }, [])
  return [value, toggle]
}