Skip to content

Instantly share code, notes, and snippets.

@ali-sabry
Created April 3, 2023 15:38
Show Gist options
  • Save ali-sabry/35b40679392b2b57f3a792abef820408 to your computer and use it in GitHub Desktop.
Save ali-sabry/35b40679392b2b57f3a792abef820408 to your computer and use it in GitHub Desktop.
This custom hook can used to manage the local and session storage and save your data such as simple string or object this hook provides a simple way to persist data across page refreshes or even between different sessions. It's a useful tool for building web applications that need to remember user preferences or other stateful information.
import { useEffect, useState } from 'react';
const useStorage = (key, initialValue, storageType) => {
let targetStorage;
/* check if the `window` object is available before using it, or to provide a fallback storage mechanism for server-
side rendering. */
if (typeof window !== 'undefined') {
targetStorage = storageType === 'sessionStorage' ? window.sessionStorage : window.localStorage;
}
let storedValue = targetStorage.getItem(key);
const [value, setValue] = useState(initialValue);
useEffect(() => {
setValue(() => {
if (storedValue !== undefined) {
return JSON.parse(storedValue);
} else {
return typeof initialValue === 'function' ? initialValue() : initialValue;
}
});
}, []);
useEffect(() => targetStorage.setItem(key, JSON.stringify(value)), [key, value, targetStorage]);
const remove = () => targetStorage.removeItem(key);
return [value, setValue, remove];
};
//=== Hook Usage
const App = () => {
// const initilVal = () => { return { name: '', email: '' } }; //== function return object
// const [user, setUser, remove] = useStorage('user', initilVal); //=== Use function as a initilVal
// const [user, setUser, remove] = useStorage('user', { name: '', email: '' }); //=== Save in localStorage
const [user, setUser, remove] = useStorage('name', { name: '', email: '' }, 'sessionStorage'); //=== Save in sessionStorage
const handleNameChange = (e) => setUser({ ...user, name: e.target.value }); //=== set the name when the user type in the input
const handleEmailChange = (e) => setUser({ ...user, email: e.target.value }); //=== set the email when the user type in the input
return (
<div>
<input type="text" value={user?.name || 'stranger'} onChange={handleNameChange} placeholder="Username" />
<input type="email" value={user?.email || 'stranger'} onChange={handleEmailChange} placeholder="Email" />
<p><span>name: {user?.name || 'stranger'}</span> <span>email: {user?.email || 'stranger'}</span></p>
<button type="button" onClick={remove}>remove storage</button>
</div>
);
}
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment