Member-only story

How to use local storage in Next js

Tushar Patel
3 min readFeb 28, 2024

--

How to use localstorage in Next js?

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>
);
}

--

--

Tushar Patel
Tushar Patel

Written by Tushar Patel

I'm a software developer passionate about using the latest technologies to create impactful applications and turn ideas into reality.

No responses yet