All files / hooks use-cached-state.ts

100% Statements 6/6
100% Branches 0/0
100% Functions 4/4
100% Lines 3/3

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                        3x   3x   3x    
import { DependencyList, useEffect, useState } from 'react';
 
/**
 * Gives you a state value that is automatically updated whenever its dependencies change.
 * @param supplier calculates the value that is stored
 * @param deps the dependencies to watch
 * @returns A state value and its setter, identical to calling `useState`
 */
export function useCachedState<T>(
  supplier: (...deps: DependencyList) => T,
  deps: DependencyList
): ReturnType<typeof useState<T>> {
  const [value, setValue] = useState<T>(() => supplier(...deps));
 
  useEffect(() => setValue(() => supplier(...deps)), deps);
 
  return [value, setValue];
}