Skip to content

Instantly share code, notes, and snippets.

@fedek6
Created August 2, 2021 20:32
Embed
What would you like to do?
Working useLocalStorage hook for Next.js (no warnings in console)
/* eslint-disable no-console */
/* eslint-disable react-hooks/exhaustive-deps */
import { useState, useEffect } from "react";
export const useLocalStorage = <T>(key: string, initialValue: T) => {
const [storedValue, setStoredValue] = useState<T | undefined>();
const setValue = (value: T) => {
window.localStorage.setItem(key, JSON.stringify(value));
};
useEffect(() => {
const value = window.localStorage.getItem(key);
if (value) {
try {
const parsed = JSON.parse(value) as T;
setStoredValue(parsed);
} catch (error) {
console.log(error);
setStoredValue(initialValue);
}
} else {
setStoredValue(initialValue);
}
}, []);
useEffect(() => {
if (storedValue) {
setValue(storedValue);
}
}, [storedValue]);
return [storedValue as T, setStoredValue] as const;
};
@Aissa-Bedr
Copy link

thanks bro.

@Antonio-Sitoe
Copy link

thanks broooo

@anthonykrivonos
Copy link

thanks bro

@highlander08
Copy link

highlander08 commented Mar 23, 2023

genioooooooo obrigado irmao

pra quem ficar com duvida usa assim. const [paragraphs, setParagraphs] = useLocalStorage('keyvalue', [])

@stefandim91
Copy link

Finally a working solution. Thanks. Can you please explain why the code doesn't throw an error (the window object is not defined) during the build process? I tried to implement a solution but I ended up getting this error.

@Antonio-Sitoe
Copy link

Antonio-Sitoe commented Apr 8, 2023

import { useState, useEffect } from "react";

export const useLocalStorage = <T,>(key: string, initialValue: T) => {
  const [storedValue, setStoredValue] = useState(() => {
    if (typeof window === "undefined") {
      return initialValue;
    }
    try {
      // Get from local storage by key
      const item = window.localStorage.getItem(key);
      // Parse stored json or if none return initialValue
      return item ? JSON.parse(item) : initialValue;
    } catch (error) {
      // If error also return initialValue
      console.log(error);
      return initialValue;
    }
  });

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

    if (storedValue) {
      setValue(storedValue);
    }
  }, [storedValue, key]);

  return [storedValue, setStoredValue];
};

@Antonio-Sitoe
Copy link

Implimentation useLocalSTorage in NextJS

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment