fix(useLocalStorage): return null after explicit removal instead of initialValue#368
Open
DISCONECTED-png wants to merge 1 commit intouidotdev:mainfrom
Open
Conversation
…nitialValue When setState(null) is called, item is removed from storage but the hook was returning initialValue instead of null. Two root causes: 1. Return line fell back to initialValue when store was null, with no way to distinguish 'never set' from 'intentionally cleared' 2. useEffect re-seeded initialValue back into storage immediately after removal Fix: track intentional removals with wasRemovedRef so both the effect and the return value handle the cleared state correctly. Fixes: uidotdev#344
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
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Problem
Calling
setValue(null)correctly removes the item fromlocalStorage,but the hook returns
initialValueinstead ofnullafter removal.Steps to reproduce:
const [value, setValue] = useLocalStorage('key', 'default');
setValue(null);
// Expected: value === null
// Actual: value === 'default'
Root Causes
Two issues working against each other:
Return value fallback —
store ? JSON.parse(store) : initialValuetreats a missing key as "never initialized" with no way to distinguish
it from an intentional removal.
Effect re-seeds storage — the
useEffectruns aftersetState(null)(because removing the item triggers a re-render) and immediately writes
initialValueback into storage, undoing the removal entirely.Fix
Added a
wasRemovedRefto track when the item is explicitly cleared.useEffectnow skips re-seeding whenwasRemovedRef.currentis truenullinstead ofinitialValuein that casekeychanges (new key = fresh initialization)Same fix applies to
useSessionStoragewhich shares the same pattern.Fixes #344