-
Notifications
You must be signed in to change notification settings - Fork 97
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
The returned setter function is changed in each render #61
Comments
Ok, I see in the code now that it is memoized and updates with the state. I guess it has to be that way. It is however a difference from how useState works, which never changes the setter function. |
I ran into this too!
I don't think it has to be this way! Here are the lines that cause use-persisted-state/src/usePersistedState.js Lines 30 to 44 in 2a33963
But it could be written like so: const persistentSetState = useCallback(
(newState) => {
setState((oldState) => {
const newStateValue = typeof newState === "function" ? newState(oldState) : newState
// persist to localStorage
set(key, newStateValue)
// inform all of the other instances in this tab
globalState.current.emit(newState)
return newStateValue
})
},
[set, key]
) By getting I believe this change would also fix #55 |
In my use case, the reason for that is the key being dynamically generated. For that to work, the function useMyHook({ id }) {
const useMyState = createPersistedState(`my-${id}`)
const [myState, setMyState] = useMyState()
// ...
} Accordingly to the library source code, the
And this param changes every time the use-persisted-state/src/index.js Line 26 in f10ad4f
Therefore, the setter changes on every render. Workaroundfunction useMyHook({ id }) {
const useMyState = createPersistedState(`my-${id}`)
const [myState, setMyState] = useMyState()
const setMyStateRef = useRef()
setMyStateRef.current = setMyState
// To set the state, setMyStateRef must be used instead of setMyState:
setMyStateRef.current(/* new value */)
} |
The setter function that is returned is not memoized, because it is always changed into a new function at each render (every invoke of the hook).
The text was updated successfully, but these errors were encountered: