Member-only story
How to use local storage in Next js
3 min readFeb 28, 2024
localStorage is a web API that allows you to store key-value pairs locally in a user's browser. It provides a simple way to store persistent data across browser sessions.
To use localStorage in a Next.js application, you can access it directly in your components or pages. Here's an example of how you can use localStorage in Next.js:
// pages/index.js
import React, { useState, useEffect } from 'react';
export default function Home() {
const [count, setCount] = useState(0);
useEffect(() => {
// Get the value from localStorage on component mount
const storedCount = localStorage.getItem('count');
if (storedCount) {
setCount(parseInt(storedCount, 10));
}
}, []);
const incrementCount = () => {
const newCount = count + 1;
setCount(newCount);
// Store the new value in localStorage
localStorage.setItem('count', newCount);
};
const resetCount = () => {
setCount(0);
// Remove the item from localStorage
localStorage.removeItem('count');
};
return (
<div>
<h1>Count: {count}</h1>
<button onClick={incrementCount}>Increment</button>
<button onClick={resetCount}>Reset</button>
</div>
);
}