Skip to content

Instantly share code, notes, and snippets.

@ynifamily3
Created December 5, 2020 08:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ynifamily3/7b60178a06e675b9a344e3abdf9a9ae8 to your computer and use it in GitHub Desktop.
Save ynifamily3/7b60178a06e675b9a344e3abdf9a9ae8 to your computer and use it in GitHub Desktop.
로컬스토리지 저장 훅
import { useState } from "react";
export function useLocalStorage<T>(
key: string,
initialValue: T
): [T, (value: T | ((val: T) => T)) => void] {
const [storedValue, setStoredValue] = useState<T>(() => {
try {
const item = window.localStorage.getItem(key);
return item ? JSON.parse(item) : initialValue;
} catch (error) {
console.error("로컬 스토리지 에러", error);
return initialValue;
}
});
const setValue = (value: T | ((val: T) => T)) => {
try {
const valueToStore =
value instanceof Function ? value(storedValue) : value;
setStoredValue(valueToStore);
window.localStorage.setItem(key, JSON.stringify(valueToStore));
} catch (error) {
console.error("로컬 스토리지 에러", error);
}
};
return [storedValue, setValue];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment