Mastering Web Storage with React: A Guide to Session and Local Storage

Jake Borromeo
4 min readDec 28, 2022

--

image: https://res.cloudinary.com/de4rvmslk/image

Are you looking to improve the user experience and functionality of your React applications? Look no further than web storage! Web storage allows you to store data on the client-side, making it easy to save user preferences, cache data, and more.

But with two types of storage to choose from — session storage and local storage — it can be tough to know which one to use and when. And how do you integrate web storage with React? In this article, we’ll explore these questions and more as we dive into the world of web storage with React.

What is Web Storage?

Web storage is a way to store data on the client-side of a web application. It allows you to save data that persists beyond a single page load, making it a useful tool for storing user preferences, cache data, and more.

There are two types of web storage: session storage and local storage. Both types of storage allow you to store data as key-value pairs, but they differ in their scope and lifetime.

Session storage is specific to a single browser tab or window and is deleted when the tab or window is closed. This makes it a useful tool for storing temporary data that is only needed within a single session.

Local storage, on the other hand, is persistent and is not deleted when the tab or window is closed. This makes it a useful tool for storing data that needs to be available across multiple sessions.

Using Web Storage in React

So how do you use web storage in a React application? The window.sessionStorage and window.localStorage objects provide methods for storing and retrieving data from web storage.

To use web storage in a React component, you can access these objects directly or create a wrapper function to handle the storage and retrieval of data. Here’s an example of a wrapper function for session storage:

const useSessionStorage = (key, initialValue) => {
const [value, setValue] = useState(
() => window.sessionStorage.getItem(key) || initialValue
);
  useEffect(() => {
window.sessionStorage.setItem(key, value);
}, [key, value]);
return [value, setValue];
};

This wrapper function uses the useState and useEffect hooks to store and retrieve data from session storage. The function takes a key and an initialValue as arguments and returns an array with the current value and a function to update the value.

To use this wrapper function in a component, you can call it like any other hook:

function MyComponent() {
const [name, setName] = useSessionStorage('name', 'Bob');
return ( <div> <input value={name} onChange={e => setName(e.target.value)} /> <p>Your name is: {name}</p> </div> );
}

In this example, the component uses the `useSessionStorage` wrapper function to store and retrieve the value of an input field in session storage. The value is saved to session storage when the input field is changed and is retrieved from session storage when the component is rendered.

You can use a similar wrapper function for local storage, or you can use the `window.localStorage` object directly. Here’s an example of how to use local storage in a React component:

function MyComponent() {
const [name, setName] = useState(window.localStorage.getItem('name') || 'Bob');
useEffect(() => {
window.localStorage.setItem('name', name);
}, [name]);
return (
<div>
<input value={name} onChange={e => setName(e.target.value)} />
<p>Your name is: {name}</p>
</div>
);
}

In this example, the component uses the useState and useEffect hooks to store and retrieve the value of an input field in local storage. The value is saved to local storage when the input field is changed and is retrieved from local storage when the component is rendered.

It’s important to note that web storage has limitations on the size and type of data that can be stored. Session storage has a limit of around 5MB, while local storage has a limit of around 10MB. Both types of storage can only store strings, so you’ll need to convert other data types to strings before storing them.

Choosing Between Session and Local Storage

So now that you know how to use web storage in React, how do you choose between session storage and local storage? Here are a few factors to consider:

  • Lifetime: As mentioned earlier, session storage is deleted when the tab or window is closed, while local storage is persistent. Choose session storage if you only need to store data for a single session, and choose local storage if you need to store data across multiple sessions.
  • Security: Local storage is stored on the client-side and is not sent to the server with HTTP requests, making it less secure than session storage. If you need to store sensitive data, it’s best to use session storage.
  • Size: Both session storage and local storage have limits on the size of data that can be stored. If you need to store large amounts of data, you may need to use a different solution such as a database or a cloud storage service.

Wrapping Up

We hope this comprehensive guide to web storage with React has given you a better understanding of how to use session storage and local storage in your applications. With the power of web storage at your fingertips, you’ll be able to create user-friendly and functional React applications that will delight your users. Happy coding!

--

--

No responses yet