Skip to content

Instantly share code, notes, and snippets.

@bantawa04
Created December 2, 2024 11:31
Show Gist options
  • Save bantawa04/e84316bf4e8e2095c2ce7136aaf9978f to your computer and use it in GitHub Desktop.
Save bantawa04/e84316bf4e8e2095c2ce7136aaf9978f to your computer and use it in GitHub Desktop.
Custom react hook for persisted state without use state
import { useState } from 'react';
export default function usePersistedState<T>(
key: string,
initialValue: T
): [T, React.Dispatch<React.SetStateAction<T>>] {
// Initialize state with a function to avoid unnecessary localStorage calls
const [value, setValueState] = useState<T>(() => {
try {
const item = localStorage.getItem(key);
// Only parse if item exists
return item ? (JSON.parse(item) as T) : initialValue;
} catch (error) {
console.warn(`Error reading localStorage key "${key}":`, error);
return initialValue;
}
});
// Wrapper function to handle both state and localStorage updates
const setValue: React.Dispatch<React.SetStateAction<T>> = (newValue) => {
try {
// Handle both direct values and updater functions
const valueToStore = newValue instanceof Function ? newValue(value) : newValue;
// Update state
setValueState(valueToStore);
// Update localStorage
localStorage.setItem(key, JSON.stringify(valueToStore));
} catch (error) {
console.warn(`Error setting localStorage key "${key}":`, error);
}
};
return [value, setValue];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment