React useSessionStorage hook

React, Hooks, State · Sep 15, 2021

Creates a stateful value that is persisted to sessionStorage, and a function to update it.

  • Use the useState() hook with a function to initialize its value lazily.
  • Use a try...catch block and Storage.getItem() to try and get the value from Window.sessionStorage. If no value is found, use Storage.setItem() to store the defaultValue and use it as the initial state. If an error occurs, use defaultValue as the initial state.
  • Define a function that will update the state variable with the passed value and use Storage.setItem() to store it.
const useSessionStorage = (keyName, defaultValue) => {
  const [storedValue, setStoredValue] = React.useState(() => {
    try {
      const value = window.sessionStorage.getItem(keyName);

      if (value) {
        return JSON.parse(value);
      } else {
        window.sessionStorage.setItem(keyName, JSON.stringify(defaultValue));
        return defaultValue;
    } catch (err) {
      return defaultValue;

  const setValue = newValue => {
    try {
      window.sessionStorage.setItem(keyName, JSON.stringify(newValue));
    } catch (err) {}

  return [storedValue, setValue];
const MyApp = () => {
  const [name, setName] = useSessionStorage('name', 'John');

  return <input value={name} onChange={e => setName(} />;

ReactDOM.render(<MyApp />, document.getElementById('root'));

Written by Angelos Chalaris

I'm Angelos Chalaris, a JavaScript software engineer, based in Athens, Greece. The best snippets from my coding adventures are published here to help others learn to code.

If you want to keep in touch, follow me on GitHub or Twitter.

More like this

  • React useLocalStorage hook

    Creates a stateful value that is persisted to localStorage, and a function to update it.

    React, Hooks · Sep 13, 2021

  • React usePersistedState hook

    Returns a stateful value, persisted in localStorage, and a function to update it.

    React, Hooks · Oct 13, 2021

  • React useMergeState hook

    Creates a stateful value, and a function to update it by merging the new state provided.

    React, Hooks · Sep 23, 2021