Creating seamless web experiences requires careful management of client-side state. One method for doing this is to use the browser feature local storage, which allows you to store data on the user's device.
Local Storage is a feature that enables websites to store key-value pairs in a web browser with no expiry date. This means the stored data remains accessible even after the user closes the browser or shuts down the system.
If you’re storing data, it means you may need to retrieve it later. Now, we’ll explore exactly how local storage works. Here’s a quick review of how it works,
“Local storage is not defined” error occurs when you are trying to access the local storage during any serverside rendering.
1
2
3
if (typeof window !== 'undefined') {
// LocalStorage code here
}
You can use lazy load your client component, make sure it's a client component, or disable pre-rendering on the server so it's only rendered on the client.
If your data is not persisting make sure that you have not accidentally cleared or you are in private browsing mode or an incognito tab.
As we discussed earlier, the local storage stores everything in a string format, so make sure you are parsing your data in the correct form,
1
const someValue = JSON.parse(localStorage.getItem('lorem') || '{}')
If you got quota exceeded error then please consider cleaning up your old or unnecessary data or take a look into using indexedDB for larger storage needs.
Solution:
You can wrap your localstorage code into try-catch block,
1
2
3
4
5
6
7
try {
localStorage.setItem('myKey', 'myValue')
} catch (e) {
if (e instanceof DOMException && e.name === 'QuotaExceededError') {
console.log("Storage full, let's make some room!")
// Handle the error (see strategies below)
}}
Remove old data,
1
2
3
4
5
const removeOldestItem = () => {
if (localStorage.length > 0) {
const oldestKey = Object.keys(localStorage)[0]
localStorage.removeItem(oldestKey)
}}
In Next.js, you can use local storage in the same way as you would in a standard React application. However, because Next.js supports Server-Side Rendering (SSR), be aware that localStorage is only accessible on the client-side (within the browser). On the server-side, there is no localStorage, so you should make sure you're accessing it only in the client environment.
Below are the steps to properly use local storage in next.js,
Step 1 : Check for client side rendering
Please first ensure that you're accessing localStorage only on the client side because it’s not available during SSR. You can do this by checking whether the code is being run in the browser (i.e., after the component mounts).
Step 2: Set up local storage access in a component
Create a new component or page where you want to use local storage.
Use the useEffect hook to ensure client-side rendering. Inside the useEffect, you can safely access localStorage because this will run only in the browser after the initial render.
Below is an example of how to use local storage in a Next.js app,
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import { useEffect, useState } from 'react';
const LocalStorageExample = () => {
// State to store the retrieved value from localStorage
const [name, setName] = useState('');
// Read from localStorage after the component mounts
useEffect(() => {
if (typeof window !== 'undefined') {
const storedName = localStorage.getItem('name');
if (storedName) {
setName(storedName);
}
}
}, []);
// Save to localStorage when the name changes
const handleNameChange = (event) => {
const newName = event.target.value;
setName(newName);
if (typeof window !== 'undefined') {
localStorage.setItem('name', newName);
}
};
return (
<div>
<h1>Welcome, {name || 'User Name'}</h1>
<input
type="text"
value={name}
onChange={handleNameChange}
placeholder="Enter your name"
/>
</div>
);
};
export default LocalStorageExample;
Below is the explanation of the above code,
LocalStorage is the storage of data directly in a user's web browser within Next.js applications. It keeps things like user preferences or settings, even after a user leaves the page or refreshes it.
When implementing it in Next.js, it's crucial to understand the distinction between server-side rendering (SSR) and client-side rendering (CSR). LocalStorage operates solely on the client side, which means it cannot be accessed during server-side rendering, so it should be used cautiously to avoid errors.
While LocalStorage is not suitable for storing sensitive data (such as passwords), it is excellent for saving preferences like a user's theme selection, language choice, or other non-sensitive settings. It's user-friendly and preserves data even after a page refresh.