CodeNewbie Community 🌱

Cover image for Saving data to localStorage using the useEffect React Hook
McKenna Bramble
McKenna Bramble

Posted on

Saving data to localStorage using the useEffect React Hook

⭐ Hello! ⭐

This post will cover saving data to localStorage by utlizing the useEffect Hook.

I have already converted the class component in this project to a function component in order to apply the useState Hook in a previous post called "Applying the useState Hook to an old React project". If you are learning about React Hooks and haven't yet had experience with the useState Hook, I would suggest reading that post first, then returning to this one!

⚑⚑⚑ I also wanted to mention that the original code that I am building off of is from a Chalkboard project I completed with Skillcrush, an online development and design school. It is self-paced and all of the classes have life-long access. This has been essential for me, as my tech journey has been anything but linear. I just wanted to give them a πŸ“’ shout-out!

πŸ€” A brief explanation of localStorage and the useEffect Hook

localStorage is a web storage object that is stored in the browser. Data that is saved in localStorage is saved in key-value pairs. This data will remain available, even if you close or refresh the browser tab.

In order to save our data to localStorage, we will be using the useEffect Hook inside of our function component. useEffect will tell React to run code every time the component renders and updates.

πŸ‘€ My project code (before the useEffect Hook)

Let's take a look at my Chalkboard project before applying the useEffect Hook.

If you toggle the view, you will see that you can add notes, but once you hit the "refresh" button, they disappear. In this post, I will be adding the useEffect Hook to save the notes to localStorage, so they do not disappear when the preview is refreshed.

πŸͺ„ Adding the useEffect Hook & utilizing localStorage

Here are the steps I took to add the useEffect Hook to my project.

1. Importing

First, you need to import useEffect from React:

import React, { useState, useEffect } from "react";
Enter fullscreen mode Exit fullscreen mode

2. Add the useEffect Hook

Inside of your function component, add the following code:

useEffect(() => {
    localStorage.setItem("stateString", JSON.stringify(notes));
  }, [notes]);
Enter fullscreen mode Exit fullscreen mode

Let's go over the code above:
A. localStorage.setItem("key", value) is the method used to add a specific key-value pair to localStorage. It accepts two arguments. The first argument is the "key" and the second is the "value".
B. The "stateString" in the code above is the "key," and the JSON.stringify(notes) is the "value" that we are assigning to the key. Later, when we fetch the data that we saved, we will do so using this "stateString" key. (Note: We need to convert the notes value to a string using the JSON.stringify() method because data can only be stored in localStorage as a string).
C. At the end of the code, we also pass the current state as a "dependency" to the useEffect Hook by adding [notes] after the setItem() method. This ensures that this Hook will only run when the notes state changes (as opposed to the chalk state, for example).

3. Add some code to the useState Hook

Right now, the initial state is set to an empty array ([]). This means that whenever we close the browser or refresh the page, our state is going to revert back to an empty array:

const [notes, setNotes] = useState([]);
Enter fullscreen mode Exit fullscreen mode

We can fix this by using the getItem() method. We will pass getItem() the key name ("stateString") that we added to localStorage in the previous step. When localStorage.getItem() is passed this key name, it returns either that key's value or null (if they key doesn't exist in localStorage).

  const [notes, setNotes] = useState(() => {
    const savedState = localStorage.getItem("stateString");
    const notes = JSON.parse(savedState);
    return notes || [];
  });
Enter fullscreen mode Exit fullscreen mode

Let's go over the code above:
A. Instead of adding an empty bracket ([]) as the initial state, we will add an arrow function that will return the saved data as the initial state.
B. Inside of the useState function, we use the localStorage.getItem() method to get the value of the "stateString" key. We save that value in the savedState variable.
C. At this point, the data that we just retrieved is still a string, so we use JSON.parse() to change it back to an array. We now save this array in the notes variable.
D. Finally, we will use the logical OR operator (||) to return either the notes array if it is available or an empty array ([]).

4. Add a refresh button

This is specific to this project, but I want to add a button that will refresh the notes array back to an empty bracket. So, I added a function:

  const refreshNotes = () => {
    setNotes([]);
  };
Enter fullscreen mode Exit fullscreen mode

And I added a button:

<button onClick={refreshNotes}>Refresh Notes</button>
Enter fullscreen mode Exit fullscreen mode

πŸ₯³ That's it!

Here is the CodeSandbox of my updated project. Feel free to toggle the preview panel to see how it is working!

⚑ Final thoughts

I have previously used componentDidUpdate() and componentDidMount() lifecycle methods inside of class components to save the state, but this was certainly a challenge. There were several resources out there that used two useEffect Hooks (one to save the data to localStorage and another to fetch it), but that way wasn't working for me. It took me awhile to figure out that I needed to add code to the useState Hook.

πŸ”— Links for additional reading

Here are some links to articles that also have great explanations of useEffect, localStorage, and BEYOND!

CopyCat Blog
Reactjs.org
freeCodeCamp

✨ Thank you for reading! ✨

Top comments (3)

Collapse
 
twosavoie profile image
Lisa Savoie

Excellent work McKenna! You've gone well beyond the scope of the lesson adding not only hooks but additional functionality. πŸ˜„

Collapse
 
mckennabramble profile image
McKenna Bramble

Thank you, Lisa!!

Collapse
 
damion_towne profile image
Damion Towne

Event production is a multidisciplinary field that encompasses a wide range of disciplines, including event planning, venue management, audio-visual equipment rentals and other services. If you looked for someone to produce your event properly then these Event Production Seattle can be very handy for you. Event production professionals are responsible for making sure that everything runs smoothly at an event. They are also responsible for ensuring that all the logistics run smoothly and safely.