[SOLVED] React App doesnt store data to local storage after refresh


This Content is from Stack Overflow. Question asked by jigantie

My react app will save data to local storage but when refreshed the data disappears. What am I doing wrong with local storage?

    import { useEffect, useState } from "react";
    import { nanoid } from "nanoid";
    import NoteList from "./components/noteList";
    import Search from "./components/search";
    import Header from "./components/header";

const App = () => {
  const [notes, setNotes] = useState([]);

  const [searchText, setSearchText] = useState("");

  useEffect(() => {
    const savedNotes = JSON.parse(localStorage.getItem("notes-data"));

    if (savedNotes) {
  }, []);

  useEffect(() => {
    localStorage.setItem("notes-data", JSON.stringify(notes));
  }, [notes]);

  const addNote = (text) => {
    const date = new Date();
    const newNote = {
      id: nanoid(),
      text: text,
      date: date.toLocaleDateString(),
    const newNotes = [...notes, newNote];

  const deleteNote = (id) => {
    const newNotes = notes.filter((note) => note.id !== id);

  return (
      <div className="container">
        <Header />
        <Search handleSearchNote={setSearchText} />
          notes={notes.filter((note) =>

export default App;

From everything that I have read I can’t see what I’m doing wrong unless its something simple.

This is pre refresh

this is post refresh


The problem is in the second useEffect hook since it is executing depending on notes array (initially is empty), this causes the localstorage data to be "erased" (in reality it is updated to an empty array after component mounts).

To understand better what I mean add a console log here to see when it is executing and what data is saved.

useEffect(() => {
console.log('saving data to local storage', notes);

localStorage.setItem("notes-data", JSON.stringify(notes));
}, [notes]);


You can handle that by stoping the useEffect execution on first render (for more information check this question)

This Question was asked in StackOverflow by jigantie and Answered by Victor It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?