Skip to main content

Command Palette

Search for a command to run...

Using localStorage in React and Next.js

Published
1 min read

We can't directly access localStorage in React and Next.js. So, for that purpose, here is the custom react hook, that will allow you to access localStorage.

import { useEffect, useState } from "react";

export function useLocalStorage<T>(key: string, initialValue: T) {
  const [storedValue, setStoredValue] = useState<T>(initialValue);
  useEffect(() => {
    const item = window.localStorage.getItem(key);
    setStoredValue(item ? JSON.parse(item) : initialValue);
  }, [initialValue, key]);

  const setValue = (value: T) => {
    setStoredValue(value);
    window.localStorage.setItem(key, JSON.stringify(value));
  };

  return [storedValue, setValue] as const;
}

If you don't want to create this hook on your own, you can simply install it using npm.

# Npm
npm install @hulkhooks/use-localstorage --save
# yarn
yarn add @hulkhooks/use-localstorage
# pnpm
pnpm add @hulkhooks/use-localstorage

Usage

import { useLocalStorage } from '@hulkhooks/use-localstorage'

function UseLocalStorageExample() {
  const [value, setValue] = useLocalStorage('key', 'default-value');
  return (
    <>
      <p>{value}</p>
      <button onClick={() => setValue('new-value')}>Set value</button>
    </>
  );
}