DEV Community

Cover image for The Basics of Local Storage in React JS!
Saleh Mubashar
Saleh Mubashar

Posted on

The Basics of Local Storage in React JS!

Hi guys!

Saving user progress and any temporary information is very essential in a web application. In React JS, this can be achieved using local Storage.


What is localStorage?

Local Storage is a web storage object to save data on a user’s computer locally, meaning it is saved in user sessions and unlike cookies, it has no expiration date. The localStorage() API allows you to access the Storage object.
We can store all kinds of data in a storage object. It is a built in hook so you do not need to import anything. The best and most common way is to first store data in a state and then in the storage object.

Creating an empty Storage object

Firstly we will create an empty storage object. I will not create an entire app in this tutorial but simply show how to use the storage object.
We will create a simple React app and inside a file, in this case App.js, and then create function called saveData(). We will run this function on a button click. I know, very simple and boing, but the objective here is to learn the localstorage api.

import { React } from "react";

function App() {
  let saveData = () =>{
    localStorage.setItem('Object 1', "test object");
  }
  return (
    <div>
      <button onClick={saveData}>Save!</button>
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

In the above code, we are creating a new storage object using setItem. 'Test object ' can be replaced by any string, state or variable.

Now, if you click the button, the text 'Test object' will be saved. But the question is, how to view the saved data as a developer?πŸ€”.

Viewing saved data

To see the data or storage object, open dev tools or inspect and go to the application tab as shown below.
Dev tools.
Next, click on the local storage option in the left menu and click on the localhost tab. The Object Object 1 will be visible.
Object.

Note!: never save sensitive or important info here. It is only used to save temporary info or user progress not things like passwords.

Saving multiple items.

We can save multiple items as separate objects or a single array in one object. However, always remember to convert an array to a string using JSON.stringify().

Retrieving stored data

We can get the saved data or use it using getItem(). In the below example, we will display the saved data using a second button.

import { React } from "react";

function App() {
  //save data
  let saveData = () =>{
    localStorage.setItem('Object 1', "test object");
  }
  //get data
  let getData = () =>{
    var data = localStorage.getItem("Object 1")
    alert(data)
  }
  return (
    <div>
      <button onClick={saveData}>Save!</button>
      <br></br>
      <button onClick={getData}>Display Info!</button>
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

Deleting Storage Objects

Storage object are never deleted automatically and must be done by either of the 2 ways:

  • Right clicking on the object in the console and deleting it
  • Create a delete function in your code.

You can use the localStorage.removeItem() method to delete and object or its contents through your code by a user event, for example.

let deleteData = () =>{
    localStorage.removeItem("Object 1")
} 
Enter fullscreen mode Exit fullscreen mode

Thank you all for reading this post!
I hope you all found the video useful.
Check out my other tutorials on hubpages.
If you like my work, you can buy me a coffee and share your thoughts πŸŽ‰β˜•
Buy Me A Coffee

Until next time!
Cheers! πŸŽ‰

Discussion (5)

Collapse
lukeshiru profile image
Info Comment hidden by post author - thread only accessible via permalink
LUKESHIRU

I recommend having 2 utils to get and save data in localStorage as JSON, so you can save objects, arrays, numbers, strings and so on:

const setLocalStorage = key => value =>
    localStorage.setItem(key, JSON.stringify(value));
const getLocalStorage = key => JSON.parse(localStorage.getItem(key));
Enter fullscreen mode Exit fullscreen mode

Once you got those, you can create a hook based on that, to integrate it better with React:

const useLocalStorage = (key, initialValue) => {
    // We use `useState` with the current value of localStorage
    // or a given initial value
    const [value, setValue] = useState(getLocalStorage(key) ?? initialValue);

    useEffect(() => {
        // Every time the value changes (or the key) we need to update localStorage
        setLocalStorage(key)(value);

        // This is a listener we will use to keep the internal state in sync
        // with localStorage, so if it changes in another tab, this tab will
        // be updated as well
        const storageSync = () => {
            const localStorageValue = getLocalStorage(key);

            return localStorageValue !== value
                ? setValue(localStorageValue)
                : undefined;
        };

        // We add the listener
        window.addEventListener("storage", storageSync);

        // And we remove it when we unmount
        return () => window.removeEventListener("storage", storageSync);
    }, [key, value]);

    // Finally we return the useState tuple, so we can use it as a useState
    return [value, setValue];
};
Enter fullscreen mode Exit fullscreen mode

And then you use it like this:

const Counter = () => {
    const [count, setCount] = useLocalStorage("count", 0);

    return <button onClick={() => setCount(count + 1)}>{count}</button>;
};
Enter fullscreen mode Exit fullscreen mode

Cheers!

Collapse
salehmubashar profile image
Saleh Mubashar Author

Yes you can, in fact this is a good approach, however in this tutorial I am only focusing on the basics of how to get and set data not to integrate it woth other react features like hooks.
Thanks!

Collapse
lukeshiru profile image
LUKESHIRU

Then why title it "Local Storage in React" if you'll not integrate it with React? You could just show localStorage without React then. I mean I get that you get more views with the #react tag, but is like I wrote an article called "Adding numbers in React" and did this:

const OnePlusOne => () => <>{1 + 1}</>
Enter fullscreen mode Exit fullscreen mode

Instead of just doing 1 + 1 😡

Thread Thread
salehmubashar profile image
Saleh Mubashar Author • Edited on

You missed my point. I could have mentioned using localstorage with hooks in details, however most of my tutorials are targeted to the beginner or intermediate audience. Besides, i mentioned several times in my post that you can use the items from local storage in any way possible, however.my focus was localstorage itself and how to get started with it.
Thanks

Thread Thread
salehmubashar profile image
Saleh Mubashar Author

Furthermore, i mentioned about JSON.stringify and how multiple objects can be saved, however i tried to keep it as simple as possible

Some comments have been hidden by the post's author - find out more