Logo

dev-resources.site

for different kinds of informations.

LocalStorage with React Hooks

Published at
7/20/2023
Categories
react
javascript
tutorial
localstorage
Author
mrrishimeena
Author
12 person written this
mrrishimeena
open
LocalStorage with React Hooks

How to Use localStorage with React Hooks to Set and Get Items

React is a popular JavaScript library for building user interfaces, and with the introduction of React Hooks, managing state and side effects has become even more straightforward. One common requirement in web development is to persist data locally, so users can access their preferences and settings across sessions. This is where localStorage comes into play. In this article, we will explore how to use localStorage with React Hooks to set and get items, providing a seamless user experience.

Understanding localStorage

localStorage is a built-in web API provided by modern web browsers that allow web applications to store key-value pairs locally within the user's browser. The data stored in localStorage persists even after the user closes the browser or navigates away from the page. This makes it an excellent choice for storing temporary or user-specific data on the client side.

React Hooks are a set of functions introduced in React 16.8 that enable developers to use state and other React features without writing a class component. By using hooks like useState and useEffect, developers can manage state and perform side effects in functional components.

Setting Up the Project

Before diving into the implementation, make sure you have a basic understanding of React and have Node.js and npm (Node Package Manager) installed on your system. Create a new React project using Create React App with the following command:

npx create-react-app localStorageExample

cd localStorageExample
Enter fullscreen mode Exit fullscreen mode

Now, let's start by creating a new functional component that will showcase the usage of localStorage:

import React from 'react'


const LocalStorageExample = () => {
  // Your code will go here
};


export default LocalStorageExample;
Enter fullscreen mode Exit fullscreen mode

Using localStorage with React Hooks

To use localStorage with React Hooks, we'll use the useState hook to manage the state and the useEffect hook to interact with localStorage.

Step 1: Import the necessary hooks and libraries

First, import the useState and useEffect hooks from React. We'll also create a simple form with an input field to demonstrate setting and getting items from localStorage:

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


const LocalStorageExample = () => {
  const [inputValue, setInputValue] = useState('');
  const [storedValue, setStoredValue] = useState('');


  useEffect(() => {
    // Your code will go here
  }, []);


  return (
    <div>
      <form>
        <input
          type="text"
          value={inputValue}
          onChange={(e) => setInputValue(e.target.value)}
        />
        <button type="submit">Save to LocalStorage</button>
      </form>
      <div>
        <h2>Stored Value:</h2>
        <p>{storedValue}</p>
      </div>
    </div>
  );
};


export default LocalStorageExample;

Enter fullscreen mode Exit fullscreen mode

Step 2: Implement the useEffect hook

Now, let's implement the useEffect hook. This hook is responsible for two tasks:

  1. Retrieving the stored value from localStorage when the component mounts.

  2. Saving the input value to localStorage when the user submits the form.


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


const LocalStorageExample = () => {
  const [inputValue, setInputValue] = useState('');
  const [storedValue, setStoredValue] = useState('');


  useEffect(() => {
    // Get the value from localStorage when the component mounts
    const storedValue = localStorage.getItem('exampleData');
    if (storedValue) {
      setStoredValue(storedValue);
    }
  }, []);


  const handleSubmit = (e) => {
    e.preventDefault();
    // Save the input value to localStorage
    localStorage.setItem('exampleData', inputValue);
    setStoredValue(inputValue);
  };


  return (
    <div>
      <form onSubmit={handleSubmit}>
        <input
          type="text"
          value={inputValue}
          onChange={(e) => setInputValue(e.target.value)}
        />
        <button type="submit">Save to LocalStorage</button>
      </form>
      <div>
        <h2>Stored Value:</h2>
        <p>{storedValue}</p>
      </div>
    </div>
  );
};


export default LocalStorageExample;

Enter fullscreen mode Exit fullscreen mode

Testing the Implementation

Now that our component is ready, we can test it by running the React development server:

npm start

Enter fullscreen mode Exit fullscreen mode

Open your browser and navigate to http://localhost:3000/ You should see the input field and a "Save to LocalStorage" button. Enter some text into the input field and click the button. The entered value will be stored in localStorage, and the "Stored Value" section will display the saved value.

Conclusion

In this article, we've explored how to use localStorage with React Hooks to set and get items, allowing us to persist data locally within a React application. By combining the useState and useEffect hooks, we can efficiently manage state and interact with localStorage without the need for class components. Remember that localStorage has limitations, such as a maximum storage capacity and that the data is specific to a domain. In cases where you need more advanced state management or data sharing between different pages or components, you might consider other options like Redux or React's Context API. However, for simple local data persistence, localStorage with React Hooks provides an elegant and straightforward solution.

localstorage Article's
30 articles in total
Favicon
É seguro guardar dados do usuário no localStorage?
Favicon
Understanding Local Storage and Session Storage in JavaScript
Favicon
How to Make localStorage Data Reactive
Favicon
Enhance React Native Security and Performance: with MMKV Storage
Favicon
# Storing Data in the Database with JavaScript
Favicon
Efficient Data Management in Manufacturing: Leveraging localStorage in Angular
Favicon
Beginner's Guide to Web Scraping and Proxy Setup with JavaScript
Favicon
Securing Web Storage: LocalStorage and SessionStorage Best Practices
Favicon
Javascript Ls/ss/cookies
Favicon
Javascript Ls/ss/cookies
Favicon
Javascript Ls/ss/cookies😎
Favicon
Faking sessionStorage to keep sites from crashing
Favicon
Elevating Data Integrity in Your React Application with Converters in Storage Management
Favicon
Storing and Testing State in localStorage with React
Favicon
Local Storage in 5 mins: A Beginner’s Guide to Cookies, localStorage, and sessionStorage
Favicon
Mastering LocalStorage Management with React Hooks
Favicon
Utilizing Local Storage in React Components: A Comprehensive Guide
Favicon
Working with JavaScript Local Storage
Favicon
LocalStorage with React Hooks
Favicon
Learn Local Storage in React: Create a Light and Dark Theme Switcher Application
Favicon
Lokalnotes - onBrowser notesapp
Favicon
Local Storage vs Session Storage in JavaScript
Favicon
Cookies vs Local Storage vs Session Storage
Favicon
How to show a pop-up only once with React, localStorage and Material UI modal
Favicon
Local Storage Bookmark Manager
Favicon
Mongez Cache, a powerful storage manager for web applications
Favicon
Using the Local Storage API in React: Creating a custom hook component
Favicon
-
Favicon
彻底弄清楚session,cookie,sessionStorage,localStorage的区别及应用场景(面试向)
Favicon
Must have Custom hooks for NextJs

Featured ones: