react-use icon indicating copy to clipboard operation
react-use copied to clipboard

setValue function in useLocalStorage hook doesn't return the correct previous value

Open vrubliuk opened this issue 1 year ago • 5 comments

import { useLocalStorage } from 'react-use';

const Demo = () => {
  const [value, setValue] = useLocalStorage('my-key', 'foo');

  return (
    <div>
      <div>Value: {value}</div>
      <button onClick={() => setValue(prev => {
        // prev value is always the same
      
         return 'bar'
      )}>bar</button>
    </div>
  );
};

What is the expected behavior? the same behavior as in useState React hook

A little about versions:

  • React: 18.2.0
  • react-use: 17.5.0

vrubliuk avatar May 21 '24 10:05 vrubliuk

Same issue here.

setStoredSelectionValue((prevValue) => ({
        ...prevValue,
        expirationDate: (new Date().getTime() + HOUR_TO_MILLISECONDS).toString(),
  }));

It returns:

{
   "expirationDate": "1728384977438",
}

Even if I had set other properties.

amaury-hanser avatar Oct 08 '24 10:10 amaury-hanser

import { useLocalStorage } from 'react-use';

const Demo = () => {
  const [value, setValue] = useLocalStorage('my-key', 'foo');

  return (
    <div>
      <div>Value: {value}</div>
      <button onClick={() => setValue(prev => {
        // prev value is always the same
      
         return 'bar'
      )}>bar</button>
    </div>
  );
};

What is the expected behavior? the same behavior as in useState React hook

A little about versions:

  • React: 18.2.0
  • react-use: 17.5.0

I don't understand what's wrong, once the localstorage exists, it will not be initialized as 'foo', it will always be 'bar' at your code

13RTK avatar Oct 09 '24 14:10 13RTK

use custom wrapper for useSafeLocalStorage

const useSafeLocalStorage = (key, initialValue) => { const [value, setValueRaw] = useLocalStorage(key, initialValue);

const setValue = (updater) => { if (typeof updater === 'function') { setValueRaw(updater(value)); } else { setValueRaw(updater); } };

return [value, setValue]; };

aryan2729 avatar Jun 03 '25 11:06 aryan2729

I am having the same problem! I am using version 17.6.0. The prevValue is not updated when the function executes, so it keeps saving the wrong value.

wsoaresfilho avatar Jun 11 '25 13:06 wsoaresfilho

I did not expect a simple bug like this could come from a 43k+ stars repo. I was criticizing my react skills until I console.logged the prevState value. And its a wonder that this issue hasn't resolved even after a year later.

Muhammed-Rahif avatar Jul 16 '25 13:07 Muhammed-Rahif