How to take advantage of Local Storage in your React projects

And why you ought to.

Ryan J. Yost
Apr 22, 2018 · 5 min read
Image for post
Image for post

Local Storage is a Web API native to modern web browsers. It allows websites/apps to store data (simple and limited) in the browser, making that data available in future browser sessions.

Before diving into the tutorial, it may be unclear why you’d want to even use Local Storage in your React apps.

There’s plenty of reasons and use cases, more than I can imagine, but here’s a few I’ve discovered.

  • A simple, fake backend for your frontend React projects — It’s often nice to add the appearance of a backend/database to your frontend portfolio projects. The extra functionality will take your app to the next level, improve the user experience and impress potential employers.
  • Experiment with different states while developing — When working on an app, it’s often useful or necessary for the app to have a certain to be able to work on particular styling and functionality, (e.g. styling a list of items and removing items requires items). Rather than recreating an app’s state on every refresh, Local Storage can persist that state, making development much more efficient and enjoyable.
  • Saving form data across sessions — what do people hate more than filling out a form? Filling out a form twice!

Quick Sidebar: I’m toying with the idea of making a React dev tool (npm package and/or chrome extension) that makes it easy to recreate your components’ state by saving old states and hydrating your components with one click. The goal would be to minimize time spent manually recreating your app’s state when developing. If you have the same pain point and would like me to build a solution, leave a comment or email me!

Getting Started

Create a new React project using create-react-app.

into the new directory and fire up the app. Install yarn if you haven’t already.

Update your with the code below. Here, we’re setting up a simple to-do list app. Absolutely nothing fancy, but it’ll do the trick for playing with .

After copying over this code, you should be able to add to-do items to the list and remove them.

Start saving things to localStorage

Saving the value of our input to is a piece of cake.

In the method, we’ll invoke the method, which takes two arguments:

  • — the name of the localStorage item
  • — the value you want to save for the given localStorage . Note: Even arrays and objects need to be saved as strings. More on that in a bit.

Here’s our new method.

As you can see, it’s not much different from updating React .

Open up the Web Developer tools in your browser of choice, find the section for Web Storage (“Application” tab in Chrome), select the current domain of and watch the value for the key stay in sync with your app’s input.

Now, let’s save the list of to-do items

When adding an item, we save the new, updated to and reset the input to a blank string.

No surprises here, except for the use of . This method converts a JavaScript value into a JSON string.

Because can only store strings, arrays and objects need to be passed into before being passed to .

Before moving on, we’ll also want to update the list in when deleting an item.

Ok, we’re saving. But watch what happens when you refresh the page…

…the reverts back to its initial state! We aren’t using the stored items yet, just saving them in the background. Not terribly helpful…

In order to persist the app’s even after refreshing the page, we need to hydrate the ‘s state with the values in , with help from a couple new methods:

  • — takes a storage and returns the value saved under that key.
  • — converts a JSON string into a JavaScript value. You need this to correctly retrieve objects and arrays that were saved as strings to .

The below method hydrates the app’s state with the values saved to . Add this new method to your component.

It makes sense to hydrate when the page loads, i.e. early on in the component lifecycle. So let’s invoke this function in .

Once you’ve added the above code to your component, refreshing the page no longer resets the app, but keeps it in sync with !

Continuously saving is unnecessary — there’s a better way.

While our app works as-is by saving React to every time the user makes an update, we don’t really need to save so frequently.

Why? Because React keeps track of the of the app throughout the user’s session — that’s what it’s for! Also, with more complex components and states, it’ll be quite cumbersome and repetitive to use wherever the is updated.

So rather than continuously keeping in-sync with React , let’s simply save to whenever the user ends their session, either by leaving the app (‘unmounting’ the component) or refreshing the page.

The new sequence of events/operations will be…

  1. The user visits the app (localhost:3000 in our case)
  2. The component mounts and hydrates its with any applicable values.
  3. React will update throughout the user’s session. won’t change.
  4. When the user ends their session, save whatever the is at that time to , making it available for hydrating in the next session.

Alright, here’s a new method for saving all of to at once. Add it to your component.

In order to save to when the user leaves the app, we need to invoke the method in .

CAVEAT — does not fire when the user refreshes or leaves the page, so we need to utilize the event to be able to save to . Learn more here.

Here’s some updated code, where we add the event listener to as well as add what we need to .

We no longer need to when updating React , so you’ll want to remove those.

A lot has changed since the beginning of the tutorial, so here’s the file at this point. *Nothing in the method has changed.*

And that’s it! You now have the tools to use Local Storage in your React projects.

React Simple Storage — an almost shameless plug

I found myself at work wanting to take advantage of Local Storage in tons of different components, so I created a component, react-simple-storage, that handles everything we’ve just implemented and much more. Keep following along to see how easy it is to use in our little to-do app.

1. Install it

2. Import it into App.js

3. Include it in your <App> component, like this…

That’s it! You don’t need all of the extra methods and event listeners from the tutorial, so the final using react-simple-storage looks like this…

HackerNoon.com

#BlackLivesMatter

Sign up for Get Better Tech Emails via HackerNoon.com

By HackerNoon.com

how hackers start their afternoons. the real shit is on hackernoon.com. Take a look

By signing up, you will create a Medium account if you don’t already have one. Review our Privacy Policy for more information about our privacy practices.

Check your inbox
Medium sent you an email at to complete your subscription.

Ryan J. Yost

Written by

Working on depchecker.com

HackerNoon.com

Elijah McClain, George Floyd, Eric Garner, Breonna Taylor, Ahmaud Arbery, Michael Brown, Oscar Grant, Atatiana Jefferson, Tamir Rice, Bettie Jones, Botham Jean

Ryan J. Yost

Written by

Working on depchecker.com

HackerNoon.com

Elijah McClain, George Floyd, Eric Garner, Breonna Taylor, Ahmaud Arbery, Michael Brown, Oscar Grant, Atatiana Jefferson, Tamir Rice, Bettie Jones, Botham Jean

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store