Created
April 3, 2023 04:00
-
-
Save jhavenz/8863d2fecb653c9d22fd99f75a9536c2 to your computer and use it in GitHub Desktop.
useStorage React Hook. Allows SessionStorage and/or LocalStorage to be used within a hook
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
# |
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 React, { useCallback, useEffect, useState } from 'react' | |
export function useLocalStorage(key, defaultValue) { | |
return useStorage(key, defaultValue, window.localStorage) | |
} | |
export function useSessionStorage(key, defaultValue) { | |
return useStorage(key, defaultValue, window.sessionStorage) | |
} | |
function useStorage(key, defaultValue, storageObject) { | |
const [value, setValue] = useState(() => { | |
const jsonValue = storageObject.getItem(key) | |
if (jsonValue != null) return JSON.parse(jsonValue) | |
if (typeof defaultValue === 'function') { | |
return defaultValue() | |
} | |
return defaultValue | |
}) | |
useEffect(() => { | |
if (value === undefined) return storageObject.removeItem(key) | |
storageObject.setItem(key, JSON.stringify(value)) | |
}, [key, value, storageObject]) | |
const remove = useCallback(() => { | |
setValue(undefined) | |
}, []) | |
return [value, setValue, remove] | |
} |
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 React from 'react' | |
export default function UseStorageExampleComponent() { | |
const [name, setName, removeName] = useSessionStorage('name', 'Kyle') | |
const [age, setAge, removeAge] = useLocalStorage('age', 26) | |
return ( | |
<div> | |
<div> | |
{name} - {age} | |
</div> | |
<button onClick={() => setName('Jimbo')}>Set Name</button> | |
<button onClick={() => setAge(40)}>Set Age</button> | |
<button onClick={removeName}>Remove Name</button> | |
<button onClick={removeAge}>Remove Age</button> | |
</div> | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment