DEV Community

Cover image for How To Set localstorage In React JS
Udemezue John
Udemezue John

Posted on

How To Set localstorage In React JS

Introduction.

When building modern web applications, managing data efficiently is key to providing a seamless user experience.

One of the most convenient ways to store user data and preferences is through the browser's local storage.

React JS, being a popular library for building user interfaces, allows me to easily integrate local storage into my applications.

Local storage provides a simple and effective means of persisting data across sessions.

According to recent statistics, around 80% of users prefer web applications that remember their preferences and past actions.

This not only enhances user satisfaction but also increases user retention and engagement.

Whether I want to save user settings, keep track of a shopping cart, or maintain application state, local storage is an invaluable tool in my development arsenal.

In this post, I’ll explore how to set and retrieve data from local storage in React JS.

What is Local Storage?

Local storage is a web storage feature that allows developers to store data as key-value pairs in a user's web browser.

This data persists even after the user closes the tab or browser, making it an excellent option for storing user preferences, session data, and other non-sensitive information.

According to a study by W3Techs, as of October 2024, over 95% of websites use client-side storage, and local storage is a vital part of that equation.

Why Use Local Storage in React?

  • Persistence: Data in local storage remains even after the page reloads, making it ideal for user settings or state that should persist.
  • Simplicity: The API is easy to use and doesn’t require any additional libraries. You can work directly with JavaScript's localStorage object.
  • Performance: Storing data in local storage is fast since it’s stored on the client side and requires no server requests.

How Do I Set localstorage In React JS?

React is a powerful library for building user interfaces, but one of the challenges developers face is managing application state across page reloads. That’s where local storage comes into play.

In this post, I'll guide you through how to set local storage in a React application effectively.

Step 1: Create a New React App.

If you haven’t already set up a React application, you can create one using Create React App. Open your terminal and run:

npx create-react-app my-app
cd my-app
npm start

Enter fullscreen mode Exit fullscreen mode

Step 2: Using Local Storage.

Here’s a simple component that allows a user to enter their name and stores it in local storage.

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

const NameStorage = () => {
  const [name, setName] = useState('');

  // Load name from local storage when the component mounts
  useEffect(() => {
    const storedName = localStorage.getItem('userName');
    if (storedName) {
      setName(storedName);
    }
  }, []);

  // Save name to local storage whenever it changes
  const handleChange = (event) => {
    setName(event.target.value);
    localStorage.setItem('userName', event.target.value);
  };

  return (
    <div>
      <h1>Hello, {name || 'Guest'}!</h1>
      <input
        type="text"
        value={name}
        onChange={handleChange}
        placeholder="Enter your name"
      />
    </div>
  );
};

export default NameStorage;

Enter fullscreen mode Exit fullscreen mode

Explanation of the Code

  • State Management: The useState hook is used to manage the name state. Initially, it’s set to an empty string.
  • Loading Data: The useEffect hook runs once when the component mounts, retrieving the stored name from local storage. If a name exists, it updates the state.
  • Saving Data: The handleChange function is called every time the input value changes. It updates the state and saves the new value to local storage.

Step 3: Rendering the Component.

To see the component in action, I can include it in the App.js file:

import React from 'react';
import NameStorage from './NameStorage';

function App() {
  return (
    <div className="App">
      <NameStorage />
    </div>
  );
}

export default App;

Enter fullscreen mode Exit fullscreen mode

Important Considerations.

While local storage is incredibly useful, it has its limitations and considerations:

  • Data Size Limit: Local storage typically allows for about 5-10 MB of data, depending on the browser. For larger data sets, consider using IndexedDB.
  • Data Security: Since local storage is accessible via JavaScript, it’s important not to store sensitive information (like passwords) in it.
  • Synchronization: Local storage does not provide automatic synchronization across different tabs or windows. If a user updates the storage in one tab, other tabs won’t reflect that change until they refresh.

Conclusion.

Incorporating local storage into a React application can significantly enhance the user experience by maintaining state across sessions.

With just a few lines of code, you can easily store and retrieve data, making your application more user-friendly.

As I continue to explore React, I find that understanding and utilizing local storage effectively can help create seamless experiences for users.

If you have any questions or need further assistance with local storage in React, feel free to reach out!

Top comments (0)