Anders Snylund’s Bulletproof TypeScript useLocalStorage hook

Published Wednesday, August 11th, 2021

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]
}
Beta

Comments, discussion & feedback.

Was this post helpful?
Does it need work? Let me know below.
No comments yet, consider adding one ☝️