For a long time, cookies were the main way to store information at the browser(client side). They were used to record stateful elements like shopping cart items or options changed by a user. They were also used to remember user browsing habits or to keep a user logged in while they went from page to page. Then, HTML5 appeared on the scene and introduced LocalStorage as another data storage option. This new Javascript object (along with SessionStorage) boasted a much large storage capacity than cookies at a whopping 5MB.
In this article, I will create a sample application to show how to use localStorage in the Reactjs application. localStorge is one of the easiest ways to store data at client-side and the best thing about local storage is that data doesn’t remove from the browser unless we remove the browser’s cache.
I will create a basic React app, in which there will be a basic user form using Bootstrap 4. In this form, I will define the title, description, and price of a document. ere with the help of localStorage, the React form state won’t change after the page refresh. we will use the React life cycle methods to set the Form state in local storage.
Create new application over terminal:
npx create-react-app local-storage-reactjs
Now, move to project folder and install bootstrap 4
npm install bootstrap --save
Add the below file path at the top of App.js file inside src folder.
import '../node_modules/bootstrap/dist/css/bootstrap.min.css';
Create new component components/AddDocument.js and put below code inside it. In this component, we will see how to save data in localStorage using Life cycle methods.
In the above code, Following task has been done:
These are the main tasks done for the storage of data in localStorage.
Run app from the terminal,
npm start
App will run on browser like below:
In this article, I explained how to use localStorage to store form or state data in Reactjs application.
You can also find other demos of React.js Sample Projects here to start working on the enterprise-level applications.
That’s all for now. Thank you for reading and I hope this demo will be very helpful for using localStorage with Reactjs form application.
Let me know your thoughts over the email demo.jsonworld@gmail.com. I would love to hear them and If you like this article, share with your friends.
Thank you!