import { useState, useEffect } from "react";

function getValue(key, initailValue) {
  const storedValue = JSON.parse(localStorage.getItem(key));
  if (storedValue) return storedValue;

  if (initailValue instanceof Function) return initailValue();
  return initailValue;

export default function useLocalStorage(key, initailValue) {
  const [value, setValue] = useState(() => {
    return getValue(key, initailValue);

  useEffect(() => {
    localStorage.setItem(key, JSON.stringify(value));
  }, [value]);

  return [value, setValue];
downloadDownload PNG downloadDownload JPEG downloadDownload SVG

Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!

Click to optimize width for Twitter