Bin
2025-12-16 9e0b2ba2c317b1a86212f24cbae3195ad1f3dbfa
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import { useState } from "react";
 
type ValueFromString<T> = (value: string) => T;
 
type ValueToString = (value: any) => string;
 
type Options<T> = {
  fromString?: ValueFromString<T>;
  toString?: ValueToString;
};
 
type StateResult<T> = [T, (value: T) => void];
 
export const useLocalStorageState = <T>(keyName: string, defaultValue: T, options: Options<T> = {}): StateResult<T> => {
  const localStorageState = localStorage.getItem(keyName);
  const defaultState = localStorageState
    ? (options.fromString?.(localStorageState) ?? (localStorageState as unknown as T))
    : defaultValue;
 
  const [state, setState] = useState<T>(defaultState);
 
  const _setInternalState = (value: T) => {
    const newValue = options?.toString?.(value) ?? (value as any).toString();
 
    localStorage.setItem(keyName, newValue);
 
    setState(value);
  };
 
  return [state, _setInternalState];
};