streamich / react-use

React Hooks — 👍
http://streamich.github.io/react-use
The Unlicense
41.98k stars 3.16k forks source link

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

Open vrubliuk opened 6 months ago

vrubliuk commented 6 months ago
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:

amaury-hanser commented 1 month ago

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.

13RTK commented 1 month ago
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