astoilkov / use-local-storage-state

React hook that persists data in localStorage
MIT License
1.17k stars 41 forks source link

Support functional lazy initializer #57

Closed mifi closed 1 year ago

mifi commented 1 year ago

First thanks for creating and maintaining this module! Looking at the docs:

The default value. You can think of it as the same as useState(defaultValue).

I would expect something like this to work:

useLocalStorageState('mykey', { defaultValue: () => someExpensiveComputation() })

because that's how useState works:

useState(() => someExpensiveComputation())

Looking at the code, it uses useRef, however useRef doesn't support functional initialzier, so this PR attempts to add support for that

astoilkov commented 1 year ago

Cool. It was working like that initially but I removed it while refactoring to simplify things. I don't remember why I didn't add it back again.

There are a few more things we should do to finish this task:

If you don't have time for these, I can do it as well. Let me know.

Thanks for the contribution!

mifi commented 1 year ago

I don't have much time these days so if you want, feel free :)

astoilkov commented 1 year ago

Yeah, I'll do it. It's a nice improvement.

astoilkov commented 1 year ago

Done. I did all tasks and published two new releases — 18.3.0 and 17.2.0.

If you are interested in the implementation — https://github.com/astoilkov/use-local-storage-state/commit/5f558840247dd6c791bcd9ccb49dee426961775c.

I even cut a few bytes off the bundle size 🤣.

Thanks for the idea.

mifi commented 1 year ago

fantastic! thanks