How to Save Data with Local Storage in React

Have you ever built a React component to display user preferences or capture to-do list items, only to see everything vanish when the page refreshes? This is where localStorage comes to the rescue! localStorage is a browser-based storage mechanism that lets you save small amounts of data directly in the user’s browser, ensuring it persists even if they close the tab or window.

In this guide, we’ll learn the fundamentals of using localStorage in React and build a practical note-taking app to see it in action.

Understanding localStorage Basics

Click Here For My Favorite Online Training For React Skills…

  • setItem() and getItem(): These are the key methods for interacting with localStorage. Let’s see an example:
  • JavaScript
  • localStorage.setItem(‘themePreference’, ‘dark’); 
  • const storedTheme = localStorage.getItem(‘themePreference’); 
  • console.log(storedTheme); // Output: ‘dark’
  • Data Types: Importantly, localStorage only stores strings. For objects or arrays, we’ll use JSON:
  • JavaScript
  • const todos = [{ task: ‘Learn React’}, { task: ‘Use localStorage’}];
  • localStorage.setItem(‘todos’, JSON.stringify(todos)); 
  • const retrievedTodos = JSON.parse(localStorage.getItem(‘todos’)); 
  • Browser Compatibility: localStorage is widely supported across modern browsers.

Building a Note-Taking App

Let’s solidify these concepts by building a simple note-taking app.

  1. Setup:
  2. Assuming you have a basic React project set up (create-react-app is a great way to start), let’s clean up our main App.js file:
  3. JavaScript
  4. import React, { useState, useEffect } from ‘react’;
  5. import ‘./App.css’; 
  6. // … (Rest of the code) 
  1. Adding Notes:
  2. JavaScript
  3. const App = () => {
  4.   const [notes, setNotes] = useState([]); // State to hold our notes
  5.   const [newNote, setNewNote] = useState(”); // State for input
  6.   const handleSubmit = (e) => {
  7.     e.preventDefault();
  8.     setNotes([…notes, { id: Date.now(), text: newNote }]); // Add new note
  9.     setNewNote(”); // Clear input
  10.   };
  11.   // … (Rest of the code) 
  12. };
    • Inside the App component, we use the useState hook to manage an array of notes and input fields.+

Displaying and Deleting Notes

Click Here For My Favorite Online Programming Course To Improve React Skills

  1. JavaScript
  2. // … (Inside the App component)
  3.  return (
  4.    <div className=”App”>
  5.      <h1>Note-Taking App</h1>
  6.      <form onSubmit={handleSubmit}> 
  7.        <input 
  8.          type=”text” 
  9.          value={newNote} 
  10.          onChange={(e) => setNewNote(e.target.value)} 
  11.        />
  12.        <button type=”submit”>Add Note</button> 
  13.      </form>
  14.      {notes.map((note) => (
  15.        <div key={note.id}>
  16.          <p>{note.text}</p> 
  17.          <button onClick={() => deleteNote(note.id)}>Delete</button>
  18.        </div>
  19.      ))}
  20.    </div>
  21.  ); 
  22. // … (Add the deleteNote function)

**4. Saving to localStorage**

“`javascript

useEffect(() => {

  const json = JSON.stringify(notes);

  localStorage.setItem(“notes”, json);

}, [notes]); // Run useEffect whenever ‘notes’ changes

5. Loading from localStorage

JavaScript

 useEffect(() => {

   const json = localStorage.getItem(“notes”);

   const loadedNotes = JSON.parse(json);

   if (loadedNotes) {

     setNotes(loadedNotes);

   }

 }, []); // Empty dependency array: run only on initial render