All files / publisher/hooks useLocalStorage.ts

80% Statements 8/10
50% Branches 3/6
80% Functions 4/5
80% Lines 8/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              162x 74x 74x               162x 74x 74x         162x         162x        
import { useState, useEffect } from "react";
 
function useLocalStorage<T = unknown>(
  key: string,
  initialValue?: T | (() => T),
): [T, (value: T | ((prevValue: T) => T)) => void] {
  // use a function to initialize the state to ensure init only runs on first render
  const [storedValue, setStoredValue] = useState<T>(() => {
    const item = window.localStorage.getItem(key);
    return item
      ? JSON.parse(item)
      : initialValue instanceof Function
        ? initialValue()
        : initialValue;
  });
 
  // when state changes update local storage
  useEffect(() => {
    setTimeout(() => {
      window.localStorage.setItem(key, JSON.stringify(storedValue));
    }, 0); // delay the write to let React do its job first
  }, [key, storedValue]);
 
  // same API as useState so we have to accept a function as argument
  const setValue = (value: T | ((prevValue: T) => T)): void => {
    const valueToStore = value instanceof Function ? value(storedValue) : value;
    setStoredValue(valueToStore);
  };
 
  return [storedValue, setValue];
}
 
export default useLocalStorage;