Jun 3, 2024

How to use Local Storage in Next.js (v14+)

#Nextjs #react #Local Storage

流逝之
by 流逝之
How to use Local Storage in Next.js (v14+)

https://dev.to/collegewap/how-to-use-local-storage-in-nextjs-2l2j

if you use like this above, you will get this error 'Text content does not match server-rendered HTML': https://nextjs.org/docs/messages/react-hydration-error , beacuse 2 and 3

To avoid the error of 'Text content does not match server-rendered HTML' when using local storage in Next.js, it's essential to ensure consistency between the server-rendered content and client-side updates. This issue can arise due to discrepancies between the initial server-rendered HTML and subsequent modifications made on the client-side. It is recommended to synchronize the content appropriately to prevent such errors.

use a custom hook to access local storage fixed:

import {useEffect, useState} from "react";

const useLocalStorage = (key: string, initialValue: any) => {
  // State to store the value
  const [storedValue, setStoredValue] = useState(initialValue);

  useEffect(() => {
    try {
      const item = window.localStorage.getItem(key);
      if (item) {
        setStoredValue(JSON.parse(item));
      }
    } catch (error) {
    }
  }, []);

  // Function to update the value in localStorage
  const setValue = (value: any) => {
    try {
      const valueToStore =
        value instanceof Function ? value(storedValue) : value;
      setStoredValue(valueToStore);
      if (typeof window !== "undefined") {
        window.localStorage.setItem(key, JSON.stringify(valueToStore));
      }
    } catch (error) {
      // console.error(error);
    }
  };

  return [storedValue, setValue];
};

export default useLocalStorage;

usage

const [bookmark, setBookmark] = useLocalStorage('Bookmark', "");

Comments(0)


Scroll down to load more data.
Continue Reading