Sign in New API Help About

848 bytes of JavaScript
Created 17 hours ago — expires in 1 day
Viewed 23 times
https://dpaste.com/7L3GYJFB8
COPY TO CLIPBOARD SOFT WRAP RAW TEXT DUPLICATE DIFF
import {useEffect, useState} from "react";

export const getLocalStorageValue = (key, defaultValue) => {
  const isClient = typeof window !== "undefined"
  if (isClient) {
    return localStorage.getItem(key) !== null
      ? JSON.parse(localStorage.getItem(key))
      : defaultValue;
  }
  return defaultValue
}

export const useLocalStorage = (key, defaultValue) => {
  const [value, setValue] = useState(() => {
    return getLocalStorageValue(key, defaultValue);
  });

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

  return [value, setValue];
};

---

const LocalStorageButton = ({
  id,
  children,
  goal,
  ...otherProps
}) => {

  return (
    <Button {...otherProps} onClick={() => useLocalStorage('goal', goal)}>
      {children}
    </Button>
  )
}

Share: