How to persist data to localStorage in React with hooks.
Tags: react, javascript, tutorial, beginners
Published: 2020-12-08 09:46:57

In my [previous post](https://dev.to/gautham495/rate-my-first-personal-react-project-and-give-feedback-24i3) 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 <strong>persistent data</strong> in your localStorage in react with hooks.

<strong>What is persistent data?</strong>

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](https://gautham-neo-budget.netlify.app/) which uses React hooks+localStorage.

This post focusses on pushing array of objects into localStorage without getting any errors.![chrome-capture (33)](https://dev-to-uploads.s3.amazonaws.com/i/xetnh87fxlhlm1t06ggn.gif)
 

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](https://gautham-neo-budget.netlify.app/).

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/0u95fzz9o642olhv64yw.gif)
Ok lets get the boilerplate done.

```js

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>
)
```

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.

```js

useEffect(()=>{

const data = localStorage.getItem('data')

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

},[])

useEffect(()=>{

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

})

```
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](https://gautham-neo-budget.netlify.app/).

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/