Created
December 17, 2023 14:36
-
-
Save phukon/af7781f002cf46f49e46f3caafb8009f to your computer and use it in GitHub Desktop.
React Hook to use local storage
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
| export const useLocalStorage = (key: string) => { | |
| const setItem = (value: unknown) => { | |
| try { | |
| window.localStorage.setItem(key, JSON.stringify(value)) | |
| } catch (error) { | |
| console.log(error) | |
| } | |
| } | |
| const getItem = () => { | |
| try { | |
| const item = window.localStorage.getItem(key) | |
| return item ? JSON.parse(item) : undefined | |
| } catch (error) { | |
| console.log(error) | |
| } | |
| } | |
| const removeItem = () => { | |
| try { | |
| window.localStorage.removeItem(key) | |
| } catch (error) { | |
| console.log(error) | |
| } | |
| } | |
| return {setItem, getItem, removeItem} | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment