I needed a simple way to use the sessionStorage
and localStorage
with React, and one of the requirements was to use TypeScript. The idea from Robin Wieruch's original article is pretty simple. It encapsulates the browser sessionStorage
or localStorage
with the useState
hook. The hooks actually return a stateful value, and a function to update it. All I had to do was to put everything together into a TypeScript module.
You can also customize the STORAGE_KEYS_PREFIX
, which can be useful to avoid conflicts between storage keys from different applications you might be developing.
If you like this post, you'll also like:
Top comments (3)
This is a cool approach for keeping data synced with storage. I faced a similar problem a while ago and came up with a not too dissimilar solution though it's more of a wrapper for storage rather than a direct line in and out of it.
React: Custom hook for accessing storage
Andrew Bone γ» Apr 21 '21 γ» 8 min read
To be honest the idea is not mine I just refined the validation a little bit and wrote it using TypeScript. I didn't credit the original author because it was late and I was tired, but as soon as I find it I'll edit the post. π
Edit: I have updated the post with a link to the original article.
Great article.
Some comments have been hidden by the post's author - find out more