astoilkov / use-local-storage-state

React hook that persists data in localStorage
MIT License
1.09k stars 39 forks source link

state is not persisted to LS during initial render with defaultValue #26

Closed quantizor closed 3 years ago

quantizor commented 3 years ago
const [locale, setLocale] = useLocalStorageState<'en-US' | 'es'>(
  'locale', 'en-US',
)

The above will not actually persist the default value to the local storage key until setLocale is called. I would expect the library to initialize the LS key with the default value if it doesn't already exist.

astoilkov commented 3 years ago

Do you have a specific use case where you need for the value to be inserted into localStorage before calling setLocale()?

Here are the reasons why I did it this way:

Both reasons aren't very important so if you have a use case I am willing to change this behavior

quantizor commented 3 years ago

Do you have a specific use case where you need for the value to be inserted into localStorage before calling setLocale()?

Well I'd expect it to work like React.setState where once you set the value, it's persisted. Very confusing behavior for you to supply a default value and not have it automatically persist to LS. Like imagine you derive a user's locale based on what URL they land on etc and then want to persist that, feeding it in as the default value. Without this behavior the only way to get it to persist is to switch it to something else and then back to the value you actually want.

astoilkov commented 3 years ago

That makes sense. I will change the behavior. Thanks.

astoilkov commented 3 years ago

@probablyup I made the change and release a new major release (because in some edge case it can become a breaking change) 10.0.0. Sorry for the delay!

quantizor commented 3 years ago

@astoilkov thank you!