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

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

})

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.

Thank you for reading!!

Check out my portfolio: Gautham’s portfolio

Check out my blog: coding-magnified.tech

Check React Project about budgeting: neo-budget

If you want to appreciate my or support me, you can buy me a coffee with the link below,

Buy Me a Coffee

My Other Articles:

Create your Web Presence with Namecheap

10 thoughts on “How to persist data to localStorage in React with hooks.”

  1. Pretty nice post. I just stumbled upon your blog and wanted to say that I’ve really enjoyed browsing your blog posts.
    In any case I’ll be subscribing to your rss feed and I hope you write again very soon!

  2. Good day! I could have sworn I’ve been to this blog before but after going through many of the posts I realized it’s new to me.

    Anyhow, I’m definitely happy I stumbled upon it and I’ll be bookmarking it and checking back regularly!

  3. I am extremely inspired with your writing abilities
    and also with the structure for your weblog. Is this a
    paid topic or did you modify it your self? Anyway stay up
    the excellent high quality writing, it is rare to see a great
    blog like this one today..

Leave a Comment

Your email address will not be published. Required fields are marked *