DEV Community

Discussion on: Please Stop Using Local Storage

Collapse
 
lsegal profile image
Loren Segal • Edited

A couple of technical corrections here about your claims that LocalStorage is "basic":

1) LocalStorage CAN be asynchonous.
2) LocalStorage CAN work with web workers.

#1 is actually possible by taking advantage of #2. By setting up a separate frame/JS exec environment, you can use standard web worker communication mechanisms of postMessage to communicate across your site. I've used this in a few apps to implement shared storage across local/remote access of a site. Doing this gives you async access, which may or may not be a good thing depending on what you're doing with localStorage, but if you're accessing a lot of data from storage it's wise to be using this method anyway.

Finally,

3) While it's true that you can only store string data, treating this as a negative is subjective. MOST key values stores (or DBs in general) treat structured data this way: MongoDB, BoltDB, even storing JSON in SQL, in all cases you're doing exactly the same thing. Sure, there's a downside for numeric primitives which SQL supports natively, but that's quite a small edge case (and for JS, passing floats around as string types is much safer). Performing serialization is a pretty standard practice in structured data cases.

And of course, having to serialize structured data is actually a decision you're making in the first place-- you can always avoid heavy serialization by restructuring your storage (using keys to namespace structures), at which point you're really only converting numerics, and that's again almost rarely a bottleneck in the grand scheme of all things JS.

I would actually argue that storing data as strings is a feature, not a bug, and a pretty standard practice for KV storage, too.

There's also a small point to be made about the 5MB limit (actually 10MB these days but who's counting) which you can workaround using methods 1&2 (granted very awkwardly), but also, you can use IndexedDB for larger data sets if you need to, you should probably only be using localStorage for state, not novel user data (like "saved content").