DEV Community

Cover image for Learn about using localStorage in Javascript and React
Gautham Vijayan
Gautham Vijayan

Posted on

Learn about using localStorage in Javascript and React

In this post, I will discuss about localStorage in JavaScript and React.js

I made my first react project using localStorage as a database.

As in react, the state vanishes when we reload the page, localStorage is the best way to persist data in a static react app.

I thought of making it with node.js and mongoose(mongodb) but localStorage was a good solution for a frontend developer like me.

LocalStorage has four methods.

  1. localStorage.setItem("data",data)
  2. localStorage.getItem("data")
  3. localStorage.removeItem("data")
  4. localStorage.remove()

We will also be using and discussing about JSON.parse() and JSON.stringify() in this post as well.

1. localStorage.setItem("data",data)

With setItem() we can set an item to localStorage which will persist even after we reload the page.

Below is an example of it.

chrome-capture (32)

A small use case can be when we click on a button, the data can be added to the localStorage.


const click = () =>{
localStorage.setItem('data','data')
}
return(
<button onClick = {click}>Click</button>
)

Enter fullscreen mode Exit fullscreen mode

We can set an object,string or even an array to the localStorage.

To know where our localStorage item is located, follow the steps below,

  • Right click and click inspect.
  • Go to application and you will find the items in the website name you are currently in.

2. localStorage.getItem("data")

After setting a data we can access the data with localStorage.getItem("data")

Here we can get the element as a string with JSON.stringify() or as an object with JSON.parse() from a string.


const data = JSON.stringify(localStorage.getItem('data'))

Enter fullscreen mode Exit fullscreen mode

We can then use this data to map out to the frontend or whatever logic you wish.

3. localStorage.removeItem("data")

With localStorage.removeItem('data') we can remove the localStorage item.

Its use case is similar to setItem() as when we want to remove an item, we click a button to do that functionality.


const remove = () =>{
localStorage.removeItem('data')
}
return(
<button onClick = {remove}>Click</button>
)

Enter fullscreen mode Exit fullscreen mode

4. localStorage.remove()

With this function we can remove all the items in one go.


const removeall = () =>{
localStorage.remove
}
return(
<button onClick = {removeall}>Click</button>
)

Enter fullscreen mode Exit fullscreen mode

And these are some of the methods and usecases on how you can use localStorage in your projects.

As a frontend developer, localStorage is a life saver as you need not know backend and database concepts like node.js and mongodb for using routes like GET,POST in our static app.

I hope this post will help you in using localStorage in your personal projects as I used this exact concept here in my previous project.

In my next post I will discussing about how you can persist data in react with react hooks, the concept which I used in my react project neo-budget

Here is the link to my next post Persist data in Local Storage with React Hooks

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:

Oldest comments (5)

Collapse
 
rxliuli profile image
rxliuli

You should also use Proxy to simplify using them

function proxyStorage(storage) {
    const kSet = new Set([
        'storage',
        'length',
        'clear',
        'getItem',
        'setItem',
        'removeItem',
        'key',
    ]);
    return new Proxy(new WebStorage(storage), {
        get(target, p, receiver) {
            if (kSet.has(p)) {
                return Reflect.get(target, p, receiver);
            }
            return safeExec(() => JSON.parse(target.getItem(p.toString())), null);
        },
        set(target, p, value, receiver) {
            if (kSet.has(p)) {
                return Reflect.set(target, p, receiver);
            }
            target.setItem(p.toString(), value !== undefined && value !== null ? JSON.stringify(value) : value);
            return true;
        },
    });
}

const store = proxyStorage(window.localStorage)
store.name = 'liuli'
console.log(store.name) // liuli
Enter fullscreen mode Exit fullscreen mode
Collapse
 
gautham495 profile image
Gautham Vijayan

Thank you for including this code here!
I will surely include this in my workflow.

Collapse
 
rxliuli profile image
rxliuli

No, you don't need it. If you use react, you should use react-use, which contains similar useLocalStorage hooks. If you plan to use it outside of react, you only need it.

Thread Thread
 
gautham495 profile image
Gautham Vijayan

I did not know, there was a option like this. I will check it out thanks.

Collapse
 
mrvijaychauhan profile image
Vijay Chauhan

localStorage.clear() for remove all localstorage