Snippets Collections
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];
}
star

Sun Jul 24 2022 20:33:08 GMT+0000 (UTC)

#react #localstorage #customhook

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension