In this short tutorial you will be shown how to store values client side in your React project.
In some cases, you may need to access some data as soon as the component mounts.
One of the options of storing particular values on the client side is using localStorage.
localStorage is similar to sessionStorage, except that while localStorage data has no expiration time. sessionStorage data gets cleared when the page session ends. localStorage data for a document loaded session is cleared when the tab is closed.
However, localStorage has limited storage capacity. Therefore, you cannot store large amount of data within it. Also, it might not be a good idea to store very sensitive data because it is vulnerable to XSS attacks.
Here is an object coming from server side:
let data = {
date: "Wed, 11 May 2022 15:10:54 GMT",
totalVisits: 15
url: "www.google.com"
}
Here is how you would store it using localStorage:
window.localStorage.setItem("data", JSON.stringify(data));
Here is how you retrieve the data:
let data = JSON.parse(window.localStorage.getItem("navItem"));
That is it! Hope it helps.