All files / react useStateWithDeps.ts

100% Statements 4/4
100% Branches 0/0
100% Functions 2/2
100% Lines 4/4

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                            20x 20x 4x   20x    
import React, { useState } from 'react'
import { useUpdateEffect } from 'react-use'
 
/**
 * 给 useState 插上依赖的翅膀。依赖变化时会更新状态。
 *
 * @param state 状态
 * @param deps 依赖
 * @returns 返回结果同 useState
 */
export function useStateWithDeps<S>(
  state: S | (() => S),
  deps: React.DependencyList,
): [S, React.Dispatch<React.SetStateAction<S>>] {
  const [value, setValue] = useState(state)
  useUpdateEffect(() => {
    setValue(state)
  }, deps)
  return [value, setValue]
}