This website uses cookies to ensure you get the best experience on our website.

Skip to content
LOGO
  • Company

    About IGNEK

    Learn about our story and our mission.

    Careers

    We're hiring!

    We always looking for talented peoples. Join our team!

    Blogs

    The latest industry news, updates and info.

    Case Studies

    Take a closer look at the projects we've delivered

    Webinar

    Watch our latest organized webinar

    Get in touch with our HR team

    • hr@ignek.com
    • +91 93284 95160
    • Ahmedabad, Gujarat, India – 382470
  • Services

    Enterprise Portal Development

    Custom Enterprise Portal Development for flawless Solutions

    Dedicated Development Team

    Expand Teams, Optimize Development with Our Expertise

    Back-end Development

    Empowering your digital presence with robust backend development expertise

    Front-end Development

    Crafting engaging user experiences through expert frontend development

    Digital Transformation

    Embrace digital transformation by modernizing process

    SaaS Development

    Transform your business with SaaS Innovative Solutions

    Technologies

    Liferay Services

    Development & Customization

    Theme

    Upgradation

    Migration

    Proof of Concept

    Performance Tunning

    Architecture

    Support & Maintenance

    E-commerce

    Expert Advice

    React Services

    Enterprise Development

    Custom Application

    Single Page Application

    Architecture

    API Integration

    Migration

    Consulting

    Maintenance & Support

    Spring Boot Services

    Web Service

    MVC Web Development

    API Integration

    Security

    Migration

    Microservices

    Support & Maintenance

    AEM Services

    Consulting Service

    Site Development

    Migration & Upgradation

    Integration

    Maintenance & Support

    Custom Solutions

    Content Management

    Team Augementation

  • Solution

    Ready for digital excellence

    In our rapidly evolving world, businesses are always on the lookout for fresh ways to improve their operations and connect with their audiences.

    Contact US

    Solutions

    SaaS : Software As A Service

    Transforming industries through cutting edge SaaS solutions.

    Customer Portal : Boost Business Productivity

    Streamline operations and enhance productivity with our Customer Portal solution.

    Liferay Based Intranet Portal

    Internal portal for company communication, collaboration and resources

    Integration

    Matomo Integration with Liferay

    Integrate Matomo to enable user interactions seamlessly.

    Microsoft Teams integration with Liferay

    Integrate to enable seamless collaboration, messaging within your portal.

    Jira Integration With Liferay

    Optimizes business operations by integrating with Jira.

  • Hire Us

    Liferay

    Get expert Liferay developers for seamless portal solutions.

    React JS

    Get expert ReactJS developers for dynamic web solutions.

    Web Developer

    Get custom web solutions from IGNEK's expert developers.

    Spring Boot

    Get top-notch Spring Boot developers for your project success!

    Healthcare

    Get top Healthcare Developers for cutting-edge medical software.

    MERN Stack

    Get expert MERN developers from IGNEK for custom, innovative project solutions.

    Why Hire Developers From IGNEK ?

    • Certified Developer
    • Transparent Communication
    • Flexible Hiring Modals
    • Fully Signed NDA
    • Cost Effective
    • Easy Exit Policy

    Get in touch with our Sales team

    • sales@ignek.com
    • +91 6351576580
    • info@ignek.com
    • Ahmedabad, Gujarat, India – 382470
SCHEDULE CALL
  • COMPANY
    • About
    • Case Studies
    • Blogs
    • Career
    • Webinar
  • SERVICES
    • Enterprise Portal Development
    • Dedicated Development Team
    • Back-end Development
    • Front-end Development
    • Digital Transformation
    • SaaS Development
  • SOLUTION
    • Customer Portal:  Boost Business Productivity
    • SaaS : Software as a Service
    • Liferay Based Employee Intranet Portal
  • TECHNOLOGY
    • Liferay Services
      • Liferay Development and Customization
      • Liferay Theme Development Service
      • Liferay DXP 7.4 Upgrade
      • Liferay Migration
      • Liferay Proof Of Concept
      • Liferay Performance Tuning
      • Liferay Architecture Design Service
      • Liferay Support And Maintenance Service
      • Liferay Ecommerce Development
      • Liferay Expert Advice
    • ReactJS Services
      • ReactJS Enterprise Application Development
      • ReactJS Custom Application Development
      • ReactJS Single Page Application Development (SPA)
      • ReactJS Applications Architecture
      • ReactJS API Integration
      • ReactJS Migration
      • ReactJS Consulting
      • ReactJS Maintenance and Support
    • Spring Boot Services
      • Spring Boot Web Development Service
      • Spring MVC Web Development
      • Spring Boot API Integration Service
      • Spring Boot Security
      • Spring Boot Migration Service
      • Spring Boot Microservices
      • Spring Boot Support & Maintenance Service
    • AEM Development Services
      • AEM Consulting Services
      • AEM Site Development
      • AEM Migration & Upgradation
      • AEM Integration Services
      • AEM Maintenance & Support
      • AEM Content Management
      • Custom AEM Solutions
      • AEM Team Augmentation
  • INTEGRATION
  • HIRE US
    • Hire Liferay Developer
    • Hire ReactJS Developer
    • Hire Spring Boot Developer
    • Hire Healthcare Developer
    • Hire Web Developer
    • Hire MERN Stack Developer
  • CONTACT US
  • Company

    About IGNEK

    Careers

    We're hiring!

    Blogs

    Case Studies

    Webinar

    Get in touch with our HR team

    • hr@ignek.com
    • +91 93284 95160
    • Ahmedabad, Gujarat, India – 382470
  • Services

    Enterprise Portal Development

    Dedicated Development Team

    Back-end Development

    Front-end Development

    Digital Transformation

    SaaS Development

    Technologies

    Liferay Liferay Services
    • Development & Customization
    • Theme
    • Upgradation
    • Migration
    • Proof of Concept
    • Performance Tuning
    • Architecture
    • Support & Maintenance
    • E-commerce
    • Expert Advice
    React React Services
    • Enterprise Development
    • Custom Application
    • Single Page Application
    • Architecture
    • API Integration
    • Migration
    • Consulting
    • Maintenance & Support
    Spring Boot Spring Boot Services
    • Web Service
    • MVC Web Development
    • API Integration
    • Security
    • Migration
    • Microservices
    • Support & Maintenance
    AEM AEM Services
    • Consulting Service
    • Site Development
    • Migration & Upgradation
    • Integration
    • Maintenance & Support
    • Custom Solutions
    • Content Management
    • Team Augmentation
  • Solution

    Ready for digital excellence

    In our rapidly evolving world, businesses are always on the lookout for fresh ways to improve their operations and connect with their audiences.

    Contact US

    Solutions

    SaaS : Software As A Service

    Customer Portal : Boost Business Productivity

    Liferay Based Intranet Portal

    Integration

    Matomo Integration with Liferay

    Microsoft Teams integration with Liferay

    Jira Integration With Liferay

  • Hire Us

    Liferay

    React JS

    Web Developer

    Spring Boot

    Healthcare

    MERN Stack

    Why Hire Developers From IGNEK ?

    • Certified Developer
    • Transparent Communication
    • Flexible Hiring Modals
    • Fully Signed NDA
    • Cost Effective
    • Easy Exit Policy

    Get in touch with our Sales team

    • sales@ignek.com
    • +91 6351576580
    • IGNEK
    • Ahmedabad, Gujarat, India – 382470
  • SCHEDULE CALL

Persisting React State in LocalStorage

  • ReactJS
  • October 18, 2024

Share On :

Introduction

In today’s web applications, providing a seamless experience across sessions is crucial for keeping users engaged. Imagine filling out a form, navigating away, and returning to find all your progress saved—this is the magic of state persistence! One popular and simple way to achieve this is through the localStorage Web API.

In this blog, we’ll walk you through how to save and restore the React state using local storage in a React TypeScript Application. We’ll cover practical examples, explore when this approach is most useful, and compare it to other storage options like session storage and cookies. 

Prerequisites
  • Node.js and npm
  • React
  • Typescript
  • JSON.parse() and JSON.stringify()
What is the LocalStorage?

Local storage is a web storage that allows users to store data as key-value pairs and retrieve the data in the browser. It’s a simple, synchronous API where the data is stored as strings and remains available even after the browser is closed, making it ideal for persisting data across sessions. 

Common Use Cases

Here are some scenarios where persisting state using local storage is beneficial:

  • Theme Persistence : Retain user preferences like light/dark themes across sessions.
  • Shopping Cart Data : Store items added to a cart so users can return later and see their selections.
  • Form Data : Persist on partially completed forms so users can complete them later without losing progress.
  • Authentication Tokens : Store JWT tokens or session information.
Key features
  • Persistent Data : Data stored in localStorage remains even after the browser is closed and re-opened. It only gets deleted if the user explicitly clears the storage or your code removes it.
  • Storage Limit : Each domain has approximately 5MB of storage available. This limit varies slightly across browsers but is usually sufficient for most use cases.
  • Stores Only Strings : localStorage can only store string data. If you need to store objects or arrays, you have to convert them to strings using JSON.stringify() and parse them back with JSON.parse() when retrieving them.
  • Synchronous API : Interacting with localStorage is synchronous, meaning it can block the main thread. For small operations, this is usually not noticeable, but for large datasets or frequent reads/writes, this can impact performance.
Methods
  • setItem() : This method allows the user to store the data as key-value pairs in local storage. It takes two parameters key and value.

Syntax : localStorage.setItem(key,value)

  • getItem() : This method allows the user to retrieve the data using the key from local storage. It accepts only one parameter, the key, and returns the value as a string.

Syntax : localStorage.getItem(key)

  • removeItem() : This method allows the user to Remove specific data using its key from localStorage. When you pass a key name to the removeItem() method, it deletes the item associated with that key from localStorage. If there’s no item with that key, this method will do nothing.

Syntax : localStorage.removeItem(key)

  • clear() :  This method allows the user to Remove all stored data from the localStorage.

Syntax : localStorage.clear()

  • key() : This method is used for the key at a specific index.

Syntax : localStorage.key(index)

  • length() : This method Gives a number of items stored in the localStorage.

Syntax : localStorage.length()

Comparison with Other Storage Types 
FeaturesLocal StorageSession StorageCookies
PersistentPersistent across browser sessionsAvailable only during the sessionCan be persistent if expiration is set
Storage Limit~5MB~5MB~4kb
Data TypeString onlyString onlyCan store any data type
ExpiresNever (unless manually deleted)When the session endsCan set expiration time
Accessed by ServerNoNoYes
Frontend Setup in React 

We’ll create a user form in React that allows users to enter their name and email. The form data will be saved to localStorage to ensure the information persists even after a page refresh or browser restart.

Step-by-step Implementation

  1. Create a React App

Let’s create a React app using the following command:

				
					//Create a react app using the following command

npx create-react-app local-storage-app --template typescript
				
			

After the setup is complete, navigate to your project folder:

				
					// Navigate to  project folder
 cd local-storage-app
 npm start

				
			

This will launch the development server, and you’ll be able to view the app at http://localhost:3000.

  1. Project Structure

Make sure your project has the following folder structure:

Image1
  1. Create the UserForm Component

We’ll create a separate UserForm component inside the components folder to handle user data entry and manage state for name and email. The component will store the data in localStorage so that it persists even after a page refresh or browser restart.

				
					//UserForm.tsx

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

interface UserData {
  name: string;
  email: string;
}

function UserForm() {
  const [name, setName] = useState<string>("");
  const [email, setEmail] = useState<string>("");
  const [userData, setUserData] = useState<UserData | null>(null);

  const addUserData = (e: React.FormEvent) => {
    e.preventDefault(); // Prevent the default form submission behavior
    localStorage.clear(); // Clears all the data
    const userData = {
      name,
      email,
    };
    localStorage.setItem("userInfo", JSON.stringify(userData));
    setName("");
    setEmail("");
  };

  const removeUserData = () => {
    localStorage.removeItem("userInfo");
    setUserData(null);
  };

  const getUserData = () => {
    const storedUserInfo = localStorage.getItem("userInfo");
    if (storedUserInfo) {
      const userInfo = JSON.parse(storedUserInfo);
      setUserData(userInfo);
    }
  };
  useEffect(() => {
    getUserData();
  }, []);
  return (
    <div className="user-form-container">
    
      <form onSubmit={addUserData} className="user-form">
      {userData && (
        <>
          <div className="user-name">
            Name: <p>{userData.name}</p>
          </div>
          <div className="user-email">
            Email: <p>{userData.email}</p>
          </div>
        </>
      )}
        <div className="user-input-group">
          <h1>Name</h1>
          <input
            placeholder="Name"
            value={name}
            onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
              setName(e.target.value)
            }
          />
        </div>
        <div className="user-input-group">
          <h1>Email</h1>
          <input
            placeholder="Email"
            value={email}
            onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
              setEmail(e.target.value)
            }
          />
        </div>
        <div className="button-group">
          <button type="submit" className="add-button">
            Add User Data
          </button>
          <button type="button" onClick={removeUserData} className="remove-button">
            Remove User Data
          </button>
        </div>
      </form>
    </div>
  );
}

export default UserForm;


				
			
  1. Integrating the Form into the App

Now, we’ll import the UserForm component into the main App.tsx file. This component will render the form UI and persist the user data.

				
					//App.tsx
import React from "react";
import UserForm from "./components/UserForm";

function App() {
  return (
    <div className="App">
      <header className="App-header">
        Persisting React state in Localstorage
      </header>

      <UserForm />
    </div>
  );
}

export default App;


				
			

Here’s a detailed breakdown of the above code and how localStorage handled the data in a react.

Storing data in the LocalStorage

When the user submits the form, the addUserData function is called. This function stores the name and email in the browser’s localStorage under the key “userInfo“.

				
					//Store data in the LocalStorage

const addUserData = (e: React.FormEvent) => {
       e.preventDefault(); // Prevent the default form submission behavior
       localStorage.clear(); // Clears all the data
       const userData = {
              name,
              email,
        };
    LocalStorage.setItem("userInfo", JSON.stringify(userData));
       setName("");
       setEmail("");
};


				
			
  • The function starts by clearing all data from localStorage using localStorage.clear(). While this ensures we are working with a clean slate, it’s important to note that it wipes out all saved data in localStorage, not just the user-related data. 
  • Next, a user data object is created, which holds the values of the name and email properties. These values are typically obtained from the form fields or state variables in React.
  • The userData object is then stored in localStorage using the localStorage.setItem() method. Since localStorage can only store strings, we use JSON.stringify() to convert the userData object into a JSON string.
  • Now, the user’s information is safely stored in localStorage under the key “userInfo”. This means you can access it later, even if the user refreshes or closes the page.
  • After saving the data to localStorage, the function calls setName(“”) and setEmail(“”) to clear the input fields, which resets the name and email state variables back to empty strings. This ensures the form fields are empty after submission.
Retrieve the data from the LocalStorage

We retrieve the stored user data using the getUserData function, which runs on component mount thanks to useEffect(). If the data exists, it is displayed in the UI.

				
					//Retrieve data in the LocalStorage

const getUserData = () => {
    const storedUserInfo = localStorage.getItem("userInfo");
    if (storedUserInfo) {
          const userInfo = JSON.parse(storedUserInfo);
          setUserData(userInfo);
      } 
};


				
			
  • To retrieve the stored user information from the localStorage using localStorage.getItem(“userInfo”), which fetches the data saved under the key “userInfo”.
  • If no data is found under the “userInfo” key, stored UserInfo will be null. That’s why we need to handle this case next.
  • If storedUserInfo is not null, it means that there is saved user information available. Since data in localStorage is stored as a string, we need to convert it back into an object. This is done using JSON.parse() method.
  • Once the userInfo object is available, we update the userData by calling setUserData() with the retrieved values.
Remove the data from the LocalStorage

Once user data is stored in localStorage, there might be situations where you want to delete it, for example, when a user logs out or resets the form. The removeUserData function demonstrates how to remove specific data from localStorage by targeting a particular key. Let’s break it down:

				
					//Remove data in the LocalStorage

const removeUserData = () => {
    const storedUserInfo = localStorage.removeItem("userInfo");
    setUserData(null);
};
				
			

The function calls localStorage.removeItem(“userInfo”) which removes the item stored under the key “userInfo” from localStorage.

The localStorage.removeItem(“userInfo”) function is used to remove the item associated with the key “userInfo” from the browser’s local storage. This targeted approach is preferable to localStorage.clear(), which deletes all items from local storage. By specifically removing only the user data linked to the “userInfo” key, we enhance security and maintain the integrity of other stored data.

Use Cases for Removing Data from LocalStorage

  • Logging Out : When a user logs out of the application, you may want to clear their data from local storage for security reasons.
  • Resetting Form : If the user resets a form or decides to start over, you can remove their previously entered data from localStorage.
Image2
Conclusion

LocalStorage is a powerful feature in React that allows developers to efficiently store and retrieve data in a user’s web browser. By leveraging localStorage, applications can persist user information and session data even after a page refresh or when the browser is closed, ensuring a seamless and personalized user experience. This capability enhances application functionality and contributes to a more user-friendly interface, enabling the creation of responsive and dynamic web applications. Ultimately, effective use of localStorage can significantly boost user satisfaction and engagement.

Explore Our Services

Discover how we can help your business thrive, whether you’re running a small startup, an SME, or a large enterprise. We’re here to understand your unique needs and goals, offering the expertise and resources to support your journey to success.

Stay informed about our ReactJS services and updates by subscribing to our newsletter—just fill in the details below to subscribe.

Loading
Loading...

Related Blogs

March 27, 2024
Authentication and Authorization in React
September 6, 2024
Creating forms in React with React Hook Form
Creating forms in React with React Hook Form
September 6, 2024
Creating forms in React with Formik
Creating forms in React with Formik
Loading...

Featured Projects Portfolios

November 27, 2023
Government Job Platform User-Friendly, Secure and Scalable
Government Job Platform : User-Friendly, Secure, and Scalable
October 4, 2023
Telecom Public Website _ Multilingual, E-Commerce, and Advanced Features
Telecom Public Website : Multilingual, E-Commerce, and Advanced Features

Digital Solutions for Your Business with IGNEK

4.9

5.0

5.0

5.0

LOGO

Making the world a better place through constructing elegant hierarchies

COMPANY

  • About
  • Career
  • Case Study
  • Blogs

SERVICES

  • Enterprise Portal Development
  • Dedicated Development Team
  • Back-end Development
  • Front-end Development
  • Digital Transformation
  • SaaS Development

HIRE US

  • Liferay
  • Spring Boot
  • ReactJS
  • Healthcare
  • MERN Stack
  • AEM

CONTACT

  • info@ignek.com
  • info@ignek.com
SALES
  • sales@ignek.com
  • (+91) 635 157 6580
CAREER
  • hr@ignek.com
  • (+91) 932 849 5160
  • E 910-912, Ganesh Glory 11, Jagatpur Road, SG Highway, Ahmedabad, Gujarat - 382470

© 2018-2025 IGNEK, Inc. All rights reserved

Linkedin Facebook X-twitter Instagram