React, losing saved data in localStorage with useEffect after page refresh

Issue

The problem is caused by the below useEffect and how you are initially setting the state:

useEffect(() => {
  localStorage.setItem('react-notes', JSON.stringify(notes));
  console.log('new note call:', notes)
}, [notes])

The above useEffect runs every time notes changes, but also on mount. And on mount the state is equal to that initial array given to useState. So the localStorage is set to that array.

Solution

A solution is to change how you are setting the state as below, so you pick what’s in the localStroge if there is something, and otherwise use that initial array you have:

const [notes, setNotes] = useState(
  !localStorage.getItem("react-notes")
    ? [
        {
          noteId: nanoid(),
          text: "This is my 1st note!",
          date: "30/07/2022",
        },
        {
          noteId: nanoid(),
          text: "This is my 2nd note!",
          date: "30/07/2022",
        },
      ]
    : JSON.parse(localStorage.getItem("react-notes"))
);

Leave a Comment