Skip to content

Instantly share code, notes, and snippets.

@joshuacerbito
Created July 25, 2019 07:10
Show Gist options
  • Save joshuacerbito/c9ff5a4ba2594127c356afa6aee761ae to your computer and use it in GitHub Desktop.
Save joshuacerbito/c9ff5a4ba2594127c356afa6aee761ae to your computer and use it in GitHub Desktop.
Custom React Hook for handling session storage
import { useState } from 'react';
export default function useSessionStorage(key, initialValue) {
const [item, setInnerValue] = useState(() => {
try {
return window.sessionStorage.getItem(key)
? JSON.parse(window.sessionStorage.getItem(key))
: initialValue;
} catch (error) {
return initialValue;
}
});
const setValue = value => {
try {
setInnerValue(value);
window.sessionStorage.setItem(key, JSON.stringify(value));
} catch (e) {
console.log(e);
}
};
return [item, setValue];
}
@Muzietto
Copy link

What about retrieving strings from the sessionStorage?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment