React 18 + LocalStorage API: How to SET Data in Browser Memory

Last Updated on by in React JS

The LocalStorage API offers a simple way to store data without using server-side databases, useful for caching user preferences, session tokens, or other small amounts of information, and this data remains even after the web page is closed and reloaded.

Today, in this post, we will show you how to store data in browser’s memory in React using the LocalStorage API and React Hooks.

Web browsers offer localStorage, a web storage API that enables web applications to store key-value pairs locally inside the user’s web browser. This storage is suitable for storing small amounts of data that the application needs to access and use across various sessions or page reloads because it persists even after the browser closes and reopens.

We will create a React application, a simple form, manage the form state using React hooks, store the form data in the browser’s local storage memory, and show you the subtle process of setting and getting the data through the localStorage API.

Let’s embark on a journey to implement localStorage in React and simultaneously set the data using the localStorage API.

Install React Project

Run the command to install a new React project.

npx create-react-app react-demo

Get into the project directory.

cd react-demo

Include Bootstrap Library

Next, run command to install bootstrap library in React app.

npm install bootstrap --legacy-peer-deps

Next, bootstrap and function component paths in src/App.js file:

import React, { Component } from "react";
import "../node_modules/bootstrap/dist/css/bootstrap.min.css";

import UserForm from "./components/UserForm";

export default function App() {
    return (
      <div className="container">
        <UserForm />
      </div>
    );
}

export default App;

React Hook Set Data in LocalStorage Example

In the following example we created a simple function component, form state contains name, email and phone number.

This data is stored in the browser storage with the help of the localStorage.setItem() and useState hook.

src/components/UserForm.js

import React, { useState, useEffect } from "react";

export default function UserForm() {
  const [formData, setFormData] = useState({
    name: "John Doe",
    email: "john@gmail.com",
    phone: "777-7777-9999",
  });

  // Form Events
  const onChangeInput = (e) => {
    setFormData((prevNext) => ({
      ...prevNext,
      [e.target.name]: e.target.value,
    }));
  };

  const onSubmit = (e) => {
    e.preventDefault();
    localStorage.setItem("user", JSON.stringify(formData));
    setFormData({
      name: "",
      email: "",
      phone: "",
    });
  };

  useEffect(() => {}, []);

  return (
    <div className=" mt-5">
      <h3>React 18 Set Data in LocalStorage Memory Example</h3>
      <div className="row">
        <div className="col-6">
          <form onSubmit={onSubmit}>
            <div className="mb-3">
              <label>Name</label>
              <input
                type="text"
                className="form-control"
                name="name"
                value={formData.name}
                onChange={onChangeInput}
              />
            </div>
            <div className="mb-3">
              <label>Email</label>
              <input
                type="email"
                className="form-control"
                name="email"
                value={formData.email}
                onChange={onChangeInput}
              />
            </div>
            <div className="mb-3">
              <label>Phone</label>
              <input
                type="tel"
                className="form-control"
                name="phone"
                value={formData.phone}
                onChange={onChangeInput}
              />
            </div>
            <button type="submit" className="btn btn-primary me-2">
              Submit
            </button>
          </form>
        </div>
      </div>
    </div>
  );
}

Test Functionality

After the user fills the information in the form, as soon as the user clicks on the submit button the form data stores in the localStorage that you can check in your browser.

How to Set Data in LocalStorage in React