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.
- Setup:
- 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:
- JavaScript
- import React, { useState, useEffect } from ‘react’;
- import ‘./App.css’;
- // … (Rest of the code)
- Adding Notes:
- JavaScript
- const App = () => {
- const [notes, setNotes] = useState([]); // State to hold our notes
- const [newNote, setNewNote] = useState(”); // State for input
- const handleSubmit = (e) => {
- e.preventDefault();
- setNotes([…notes, { id: Date.now(), text: newNote }]); // Add new note
- setNewNote(”); // Clear input
- };
- // … (Rest of the code)
- };
-
- 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
- JavaScript
- // … (Inside the App component)
- return (
- <div className=”App”>
- <h1>Note-Taking App</h1>
- <form onSubmit={handleSubmit}>
- <input
- type=”text”
- value={newNote}
- onChange={(e) => setNewNote(e.target.value)}
- />
- <button type=”submit”>Add Note</button>
- </form>
- {notes.map((note) => (
- <div key={note.id}>
- <p>{note.text}</p>
- <button onClick={() => deleteNote(note.id)}>Delete</button>
- </div>
- ))}
- </div>
- );
- // … (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
- Heroku vs Azure
- Your Guide to Netlify CMS
- How to use React Icons in Your Projects
- What Is PHP Hosting
- How To Super Charge Learning CSS
- This One Hosting Trick Netlify Doesn’t Want You To Know…
- How To Use SCSS In HTML
- Building the Ultimate React To-Do List: A Step-by-Step Guide
- Different ways to use CSS
- How to Set up a React Webpack Application