React JS : Save Data in Local Storage, Get Data

How to save data to browser storage in our React JS App. If we are storing the data to the local storage of the browser then the data won’t be lost while the webpage is refreshed. We can save temporary data that we have fetched or data in the states like this. So the next time, while we open the page data, will be there.

We will be quickly looking at two local storage functions. One is setItem() to store the data to local storage. The other one is getItem() to get the saved data from the local storage.

Save Data to Browser Local Storage using – setItem()

window.localStorage.setItem('name', nameInput);
window.localStorage.setItem('email', emailInput);

In the above code nameInput, emailInput are variables containing the input data that we can receive from the input form of the webpage.

Both the data are stored to localStorage of the browser using the setItem() function to corresponding item keys: name, email. These keys can be used to fetch the saved data from the browser’s local storage.

Load Data from Browser Local Storage using – getItem()

const user_name = window.localStorage.getItem('name') || '' ;
const user_email = window.localStorage.getItem('email') || '' ;

In the above code, we are using the localStorage data and taking it to our user_name, user_email. If the keys: name, email are available then that data will be fetched else empty string will be saved to our const data.

React JS : Save Data in Local Storage, Get Data

You can find example usage of the browser localStorage. Code, output, and browser storage fields are also shown. Similarly, we can make use of the browser localStorage in or React Apps or other Javascript apps.

About the Author: smartcoder

You might like

Leave a Reply

Your email address will not be published.