Using localStorage in React Applications

thequeenbeebs
3 min readAug 8, 2021
Photo by Ferenc Almasi on Unsplash

Who can remember all of our usernames and passwords these days anyways? Those “Remember Me” checkboxes at the bottom of login forms have really come in handy in this day and age, and the way that is done is by saving that sort of data on the user’s machine. A simple way to do that is through localStorage! Today, I’m going to walk through exactly what localStorage is, how to find it on your DevTools, and a couple of important functions in order to implement it into your own React applications.

What is localStorage?

My favorite definition is from LogRocket:

localStorage is a property that allows JavaScript sites and apps to save key-value pairs in a web browser with no expiration date. This means the data stored in the browser will persist even after the browser window is closed.

In the past, I have only used localStorage for authorization and authentication usage, but this week I was given a take-home assignment for a company that asked me to keep the state on my application persistent “even if the server has restarted.” I know there are probably more secure ways to handle such problems, but I knew that localStorage would be there in a pinch to help me out!

Finding localStorage in your DevTools

For me, the thing that really helped me understand localStorage and how it works was to find and play with it in my DevTools! Of course every browser is going to be different, but today I will walk you through finding it on Google Chrome.

1. Right click on your application, and select “Inspect”

2. Click on the >> dropdown menu and then select Application.

3. Click on the localStorage button to see all of the key-value pairs!

There you have it! This really comes in handy with debugging and making sure your localStorage is working like you’d like it to! Now, let’s move on to a couple of commonly used methods in order to implement localStorage in your application.

localStorage.setItem()

localStorage.setItem adds a key and value pair to your localStorage, taking two arguments like so:

localStorage.setItem('name', 'Blaire');

In this instance, it would save the string ‘Blaire’ in localStorage under the key of ‘name’.

localStorage.getItem()

Now, let’s say we want to retrieve a piece of useful information from localStorage…we would use the getItem method, which use takes just one argument: a key.

localStorage.getItem('name') /// 'Blaire'

Now, we are calling on localStorage and asking it to return the value that is signed to a particular value. Not too difficult, right?

Putting It All Together

Now, I’m going to show you a bit of how I used localStorage in action!

What I wanted to do was check and see if localStorage already had a value connected to the key of userData. If it did, I would set my state to that value. If not, I would make a fetch request to the API to get the data I needed. This is how I did it:

useEffect(() => {   if (localStorage.getItem('userData')) {      setUserData(JSON.parse(localStorage.userData))   } else {      fetch(`http://localhost:3000/users/${userId}`)         .then(resp => resp.json())         .then(data => {            setUserData(data)            localStorage.setItem('userData', JSON.stringify(data))      })   }}, [])

HINT: localStorage can only take strings for values. If you need to use another data type, like I did with an array of objects, all you need to do call on JSON.stringify() to turn that array into a string, and parse that string when you get it back!

Play around with it, and make sure to take advantage of your DevTools when debugging. Happy coding!

--

--

thequeenbeebs

Blaire is a musical theatre performer who also moonlights as a full-stack software engineer. https://www.linkedin.com/in/blaire-baker