stephen.news

hypertext, words and more

Anders Snylund’s Bulletproof TypeScript useLocalStorage hook

I’ve found myself using localStorage more and more these days. Turns out there’s a fancy hook for that. Not surprised! But where’s the love for TypeScript?

Turns out, Anders has done the refactoring for us:

import { useState } from "react";

export const useLocalStorage = <T>(key: string, initialValue: T): [string, typeof setValue] => {
  const [storedValue, setStoredValue] = useState(() => {
    try {
      const item = window.localStorage.getItem(key)
      return item ? JSON.parse(item) : initialValue
    } catch (error) {
      return initialValue
    }
  });

  const setValue = (value: T): void => {
    try {
      const valueToStore = value instanceof Function ? value(storedValue) : value
      setStoredValue(valueToStore)
      window.localStorage.setItem(key, JSON.stringify(valueToStore))
    } catch (error) {
      return error
    }
  };

  return [storedValue, setValue]
}