Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

604 B
Raw Blame
import { useEffect, useState } from "react";

type TPersisntentStateReturn<T> = [T, (val: T) => void];

export const usePersistentState = <T>(
  initialValue: T,
  persistenceKey: string
): TPersisntentStateReturn<T> => {
  const [val, setVal] = useState<T>(initialValue);

  useEffect(() => {
    const temp = localStorage.getItem(persistenceKey);
    if (temp) {
      const { key } = JSON.parse(temp);
      setVal(key);
    }
  }, []);

  const setState = (state: T) => {
    localStorage.setItem(persistenceKey, JSON.stringify({ key: state }));
    setVal(state);
  };

  return [val, setState];
};