Created
December 5, 2020 08:42
-
-
Save ynifamily3/7b60178a06e675b9a344e3abdf9a9ae8 to your computer and use it in GitHub Desktop.
로컬스토리지 저장 훅
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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