Skip to content

Instantly share code, notes, and snippets.

@emekaorji
Last active February 8, 2024 23:03
Show Gist options
  • Save emekaorji/4221fe5843589db0d71d422b3cb6a821 to your computer and use it in GitHub Desktop.
Save emekaorji/4221fe5843589db0d71d422b3cb6a821 to your computer and use it in GitHub Desktop.
A react hook to establish a sync with the electron store with real-time updates.
import { Dispatch, SetStateAction, useEffect, useRef, useState } from 'react';
function useStoreState<T>(
_key: string,
_initialValue: T | (() => T)
): [T, Dispatch<SetStateAction<T>>];
function useStoreState<T = undefined>(
_key: string
): [T | undefined, Dispatch<SetStateAction<T | undefined>>];
function useStoreState<T = undefined>(
key: string,
initialValue?: T | (() => T)
) {
const [value, setValue] = useState(() => {
try {
const storedValue = window.electron.store.get(key);
return storedValue ? (JSON.parse(storedValue) as T) : initialValue;
} catch (error) {}
return initialValue;
});
const currentKey = useRef(key);
useEffect(() => {
let _value: T | undefined;
if (currentKey.current !== key) {
_value = window.electron.store.get(key);
currentKey.current = key;
setValue(value ?? initialValue);
} else {
_value = value;
}
window.electron.store.set(key, _value);
}, [initialValue, key, value]);
return [value, setValue] as const;
}
export default useStoreState;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment