React useSessionStorage Hook

ReactReactBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will be learning how to use the useSessionStorage hook in React to persist stateful values to sessionStorage. We will learn how to initialize the value lazily, retrieve and store values using Storage.getItem() and Storage.setItem(), and how to update the state variable using the defined function. By the end of this lab, you will have a better understanding of how to use sessionStorage to store and retrieve data within a React application.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL react(("`React`")) -.-> react/FundamentalsGroup(["`Fundamentals`"]) react(("`React`")) -.-> react/AdvancedConceptsGroup(["`Advanced Concepts`"]) react(("`React`")) -.-> react/StateManagementGroup(["`State Management`"]) react/FundamentalsGroup -.-> react/jsx("`JSX`") react/FundamentalsGroup -.-> react/event_handling("`Handling Events`") react/AdvancedConceptsGroup -.-> react/hooks("`React Hooks`") react/StateManagementGroup -.-> react/use_state_reducer("`Using useState and useReducer`") subgraph Lab Skills react/jsx -.-> lab-38408{{"`React useSessionStorage Hook`"}} react/event_handling -.-> lab-38408{{"`React useSessionStorage Hook`"}} react/hooks -.-> lab-38408{{"`React useSessionStorage Hook`"}} react/use_state_reducer -.-> lab-38408{{"`React useSessionStorage Hook`"}} end

React useSessionStorage Hook

index.html and script.js have already been provided in the VM. In general, you only need to add code to script.js and style.css.

To create a stateful value that is persisted to sessionStorage, and a function to update it, follow these steps:

  1. Use the useState() hook with a function to initialize its value lazily.
  2. 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.
  3. Define a function that will update the state variable with the passed value and use Storage.setItem() to store it.

Here is an example implementation:

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) {}
    setStoredValue(newValue);
  };

  return [storedValue, setValue];
};

You can use this hook in your app like this:

const MyApp = () => {
  const [name, setName] = useSessionStorage("name", "John");

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

ReactDOM.createRoot(document.getElementById("root")).render(<MyApp />);

Please click on 'Go Live' in the bottom right corner to run the web service on port 8080. Then, you can refresh the Web 8080 Tab to preview the web page.

Summary

Congratulations! You have completed the React useSessionStorage Hook lab. You can practice more labs in LabEx to improve your skills.

Other React Tutorials you may like