DEV Community

Cover image for How to persist data to localStorage in React with hooks.
Gautham Vijayan
Gautham Vijayan

Posted on • Updated on

How to persist data to localStorage in React with hooks.

In my previous post I shared my new react project where I used data visualization with pie chart in my app in a small scale.

I should have made a backend server but instead I used localStorage to satisfy all my needs.

In this post I will discuss how you can have persistent data in your localStorage in react with hooks.

What is persistent data?

In a react app if you reload the page, all the state vanishes.

If you want to push an array of object to localStorage with useState and getting all sorts of errors like state vanishing after the page loading, you are at the right place because I solved this issue and deployed my react-project which uses React hooks+localStorage.

This post focusses on pushing array of objects into localStorage without getting any errors.chrome-capture (33)

In order to tackle this issue, we can use useEffect to our advantage.

We are going to use not one but two useEffect hooks in our app.

Ok let me first explain what we are going to do.

We are going to create a react app which will get data from the user and send array of objects to the localStorage and map it and display its elements in the frontend like my project.

Alt Text
Ok lets get the boilerplate done.


import React, { useState,useEffect } from 'react';
const Form = () => {
  const [name, setname] = useState('')
  const [price,setprice]=useState('')
  const [item,setitem]=useState([]) 

const handleSubmit = (e) => {

    e.preventDefault();
    setitem([...item,{name:name,price:price}])
    setname('')
    setprice('')

  };

return(
<form onSubmit={handleSubmit}>

<input type = "text" name="name" value={name} onChange={(e) => setname(e.target.value)}/>

<input type = "number" name="price" value={price} onChange={(e) => setprice(e.target.value)}/>

<input type = "submit"/>

</form>
)
Enter fullscreen mode Exit fullscreen mode

Now here comes the useEffect part.

We will be using two useEffect hooks in here to store array of object data into localStorage and fetching it to show it in the frontend.

The first useEffect hook will get the items from localStorage and set it to the 'item' useState array when the page first loads.

Then the second useEffect hook will set the items to localStorage whenever the state (that is the item) changes.


useEffect(()=>{

const data = localStorage.getItem('data')

if(data){
  setitem(JSON.parse(data))
 }

},[])

useEffect(()=>{

  localStorage.setItem('data',JSON.stringify(item))

})

Enter fullscreen mode Exit fullscreen mode

If you execute this perfectly you can now access localStorage as a database to get and post data to it like I did in my project.

The only downside to this is all the elements are stored as JSON strings and you need some ways to get over this with parseInt().

And that's how you can use React Hooks with localStorage to make a database within the browser itself.

To know more about React & React Native you can checkout my courses in Udemy.

https://www.udemy.com/course/react-native-for-absolute-beginners-with-react-hooks/

Top comments (6)

Collapse
 
wseai profile image
jagarkin • Edited

using localStorage as a database for your project, is not a good practice for many reasons:

  • It can only store string data (you could serialize everything including data types into local storage, but that's an ugly hack.)

  • It is synchronous ( This means each local storage operation you run will be one-at-a-time it will slow your app )

  • It can't be used by web workers ( This means that if you want to build an application that takes advantage of background processing for performance, chrome extensions, things like that: you can't use local storage at all since it isn't available to the web workers. )

  • It still limits the size of data you can store ( 5mb )

  • unprotected JavaScript ( vulnerable to XSS )

  • when user clear cache data will be lost

Collapse
 
gautham495 profile image
Gautham Vijayan

Yes sir for a personal project for beginners it is a good hack to learn. But for a production app, no way I am using localstorage.
Cheers.

Collapse
 
muhfaridzia profile image
Muhammad Farid Zia

The second useEffect is wrong, coz your useEffect will run every render, you should put deps in the second useEffect parameter.

Collapse
 
gautham495 profile image
Gautham Vijayan

No farid, I can even share my source code, It works absolutely fine.

Collapse
 
muhfaridzia profile image
Muhammad Farid Zia

Yaps, your code work, but your second useEffect will run every render because you omit deps, that's the problem.

reactjs.org/docs/hooks-effect.html...

Thread Thread
 
gautham495 profile image
Gautham Vijayan

Naa bro! It works, You can go and check my project's console