useLocalStorage

useLocalStorage
useLocalStorage.js
import React from "react"

export const useLocalStorage = (key, initialValue) =>{
    const [storedValue, setStoredValue] = React.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;
      }
    });

    const setValue = (value) => {
      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.log(error);
      }
    };
    return [storedValue, setValue];
  }

Why?

This hooks is used to sync state to local storage so that it persists through a page refresh.

Usage is similar to useState except we pass in a local storage key so that we can default to that value on page load instead of the specified initial value.

Since the local storage API isn't available in server-rendering environments, we check that typeof window !== "undefined" to make SSR and SSG work properly.

Usage

1

Basic Usage

const Page = () => {
	const [name, setName] = useLocalStorage("name");

    if(!name) {
        setName("John Doe");
    }

    return (
        <>{name}</>
    )
}