Firstly, we will see what is localStorage. As the name suggest, it is a web storage that stores the application data locally in your browser.
Above all, The reason why we need to store the data in the browser. let's say that you want to persist the data even after refreshing the browser, using local storage is a one of the popular methods.
Basically, there are different methods to access and manipulate the data in the localStorage. they are,
Mainly, getItem is used to get the item stored in the localStorage using the key.
it takes the key as the parameter and returns you the value for the associated key.
basically, the above code will return the value for the key user in the localStorage.
localStorage uses setItem to insert a value. it stores as key value pair.
Once you store the value, you can access it using the key.
Above all, you can store any kind of primitive data structures inside the localStorage.
For example, it can be an object, array or string. On the other hand, make sure to store it as JSON.
Likewise, the name itself explains the functionality of this method. it removes an item from the localStorage.
To remove an item from localStorage, you can use the key to access and remove it.
above code will the remove the item with the key userData from the localStorage
After that, clear is to remove all the items from the localStorage. it will be useful when you want to remove all the items from the localStorage for the particular domain.
Most importantly, when you are in a browser tab, it will show all the localStorage items only for the current tab, not for the entire browser localStorage items.
Although localStorage is so popular. but, there are few limitations in using localStorage in our applications. they are,
Let's take slack as an example for this use- case.
firstly, Slack stores the session tokens, activity and message input in the localStorage.
Most importantly , localStorage stores the data with user id prefixed in the keys.
For example, the custom emoji is stored in the localStorage with the key like <user_id>_custom_emoji
Surprisingly, slack stores some of the localStorage data in the binary format.