react-hookz / web

React hooks done right, for browser and SSR.
https://react-hookz.github.io/web/
MIT License
1.91k stars 91 forks source link

State updates in useLocalStorageValue are not queued like useState is. #1507

Open rstepinski opened 9 months ago

rstepinski commented 9 months ago

Prior Issues

none

What is the current behavior?

Using multiple state updates from useLocalStorageValue, be it in different components or sequentially in the same component, are not queued. The last state update receives the initial state and not the state already altered by previous updates.

Steps to Reproduce

Consider the following code:

const { set } = useLocalStorageValue<number, number, true>('test', { defaultValue: 0 });

set((prev) => {
  console.log(prev); // Expect 0
  return prev + 1;
});
set((prev) => {
  console.log(prev); // Expect 1
  return prev + 1;
});
set((prev) => {
  console.log(prev); // Expect 2
  return prev + 1;
});

All set calls will receive 0.

What is the expected behavior?

State updates should be queued to allow for sequential state updates. If this is not possible, it should be clearly mentioned in the documentation that the expected behavior differs from what we're used to with useState.

Environment Details