use-persisted-state icon indicating copy to clipboard operation
use-persisted-state copied to clipboard

Initial state

Open danielkcz opened this issue 6 years ago • 3 comments

I definitely like the idea and mostly of how it's implemented, but the somewhat big caveat to me as DRY guy is repeating the initial state. I mean with regular useState it does make sense as it's isolated but looking at this like a "shared" state, there should definitely be a single place to declare initialState.

I would propose to expand API like createPersistentState(key, initialState). I know there is another argument for storage, but that's likely to be used rarely, so it can be at 3rd place just fine :) Alternatively, it could make sense to export another function with currying behavior where storage would be specified in the first argument and it would return factory bound to that storage type.

Of course, it would still be possible to specify an initial state directly in a component, but it would be optional. Perhaps it could even show DEV-only warning to keep such state unified.

danielkcz avatar Oct 05 '19 18:10 danielkcz

I'm very interested in this behavior. Do you want this as PR @donavon or is it more of a fork addition?

karlsander avatar Feb 07 '20 13:02 karlsander

+1

I have new Set() as initialState foruseState(), and in every moment that I persist to localStorage I have to make transformations (not very performant). Adding a transform param also might come in handy idk

FMGordillo avatar Feb 28 '20 19:02 FMGordillo

I have made a module that solves this problem by making a special function called createLocalStorageStateHook(key, initialState?) you can take a look at it https://github.com/astoilkov/use-local-storage-state.

astoilkov avatar Mar 14 '20 19:03 astoilkov