Advertisement
ValentinBoba

Untitled

May 15th, 2024
777
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import { useEffect, useState } from 'react';
  2.  
  3. const isClient = typeof window === 'object';
  4.  
  5. type Dispatch<A> = (value: A) => void;
  6. type SetStateAction<S> = S | ((prevState: S) => S);
  7.  
  8. export const useLocalStorage = <T>(
  9.   key: string,
  10.   initialValue?: T,
  11.   raw?: boolean
  12. ): [T, Dispatch<SetStateAction<T>>] => {
  13.   if (!isClient) {
  14.     return [initialValue as T, () => {}];
  15.   }
  16.  
  17.   const [state, setState] = useState<T>(() => {
  18.     try {
  19.       const localStorageValue = localStorage.getItem(key);
  20.       if (typeof localStorageValue !== 'string') {
  21.         localStorage.setItem(key, raw ? String(initialValue) : JSON.stringify(initialValue));
  22.         return initialValue;
  23.       } else {
  24.         return raw ? localStorageValue : JSON.parse(localStorageValue || 'null');
  25.       }
  26.     } catch {
  27.       // If user is in private mode or has storage restriction
  28.       // localStorage can throw. JSON.parse and JSON.stringify
  29.       // can throw, too.
  30.       return initialValue;
  31.     }
  32.   });
  33.  
  34.   useEffect(() => {
  35.     try {
  36.       const serializedState = raw ? String(state) : JSON.stringify(state);
  37.       localStorage.setItem(key, serializedState);
  38.     } catch {
  39.       // If user is in private mode or has storage restriction
  40.       // localStorage can throw. Also JSON.stringify can throw.
  41.     }
  42.   }, [state]);
  43.  
  44.   return [state, setState];
  45. };
  46.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement