Custom Hooks — Intermediate React challenge.
Build a generic useLocalStorage hook from scratch, then use it to power a persisted counter with Increment, Set-to-100, and Reset — no libraries, no pre-built markup.
Requirements
- useLocalStorage(key, initialValue) returns [value, setValue, removeValue], mirroring useState's API.
- On mount, reads and JSON.parses any existing value under 'key'; falls back to initialValue if missing or invalid.
- setValue accepts either a direct value or a functional updater (prev => next), just like useState.
- Every successful setValue call writes the new value to localStorage as JSON.
- removeValue deletes the localStorage key entirely and resets state back to initialValue.
- Corrupted/invalid JSON already in localStorage must not crash the component on mount.
Signature
function useLocalStorage(key: string, initialValue: any): [any, (value: any) => void, () => void]
Example
const [count, setCount, resetCount] = useLocalStorage("reactgrind-counter-demo", 0);
// setCount(prev => prev + 1) -> increments and persists
// setCount(100) -> sets directly and persists
// resetCount() -> clears storage, count back to 0Constraints
- Must support both call styles of setValue: direct value and functional updater.
- Must never throw on invalid JSON already present in localStorage — fall back silently to initialValue.
- removeValue must fully clear the key from localStorage, not just reset in-memory state.