Created
December 2, 2024 11:31
-
-
Save bantawa04/e84316bf4e8e2095c2ce7136aaf9978f to your computer and use it in GitHub Desktop.
Custom react hook for persisted state without use state
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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