todo-next

yet another task list webapp, made with Next.js
Log | Files | Refs | README

useLocalStorage.ts (657B)


      1 "use client";
      2 
      3 import { Dispatch, SetStateAction, useEffect, useState } from "react";
      4 
      5 function getStorageValue<T>(key: string, defaultValue: T) {
      6   const saved = window.localStorage.getItem(key);
      7   if (!saved) return defaultValue;
      8   const initial = JSON.parse(saved) as T;
      9   return initial || defaultValue;
     10 }
     11 
     12 export const useLocalStorage = <T>(
     13   key: string,
     14   defaultValue: T,
     15 ): [T, Dispatch<SetStateAction<T>>] => {
     16   const [value, setValue] = useState<T>(() => {
     17     return getStorageValue(key, defaultValue);
     18   });
     19 
     20   useEffect(() => {
     21     window.localStorage.setItem(key, JSON.stringify(value));
     22   }, [key, value]);
     23 
     24   return [value, setValue];
     25 };