And why you ought to.
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
state
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!
Getting Started
Create a new React project using create-react-app.
npx create-react-app local-storage
cd
into the new directory and fire up the app. Install yarn if you havenāt already.
yarn start
Update your App.js
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 localStorage
.
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 newItem
input to localStorage
is a piece of cake.
In the updateInput()
method, weāll invoke the [localStorage.setItem()](https://developer.mozilla.org/en-US/docs/Web/API/Storage/setItem)
method, which takes two arguments:
key: string
āāāthe name of the localStorage itemvalue: string
āāāthe value you want to save for the given localStoragekey
. Note: Even arrays and objects need to be saved as strings. More on that in a bit.
Hereās our new updateInput()
method.
As you can see, itās not much different from updating React state
.
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 localhost:3000
and watch the value for the newItem
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 list
to localStorage
and reset the newItem
input to a blank string.
No surprises here, except for the use of [JSON.stringify()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify)
. This method converts a JavaScript value into a JSON string.
Because localStorage
can only store strings, arrays and objects need to be passed into **JSON.stringify()**
before being passed to **setItem()**
.
Before moving on, weāll also want to update the list in localStorage
when deleting an item.
Ok, weāre saving. But watch what happens when you refresh the pageā¦
ā¦the App
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 state
even after refreshing the page, we need to hydrate the App
ās state with the values in localStorage
, with help from a couple new methods:
[localStorage.getItem()](https://developer.mozilla.org/en-US/docs/Web/API/Storage/getItem)
āāātakes a storagekey
and returns the value saved under that key.[JSON.parse()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse)
āāāconverts a JSON string into a JavaScript value. You need this to correctly retrieve objects and arrays that were saved as strings tolocalStorage
.
The below method hydrates the appās state with the values saved to localStorage
. Add this new method to your App
component.
It makes sense to hydrate state
when the page loads, i.e. early on in the component lifecycle. So letās invoke this function in componentDidMount()
.
Once youāve added the above code to your App
component, refreshing the page no longer resets the app, but keeps it in sync with localStorage
!
Continuously saving is unnecessaryāāāthereās a better way.
While our app works as-is by saving React state
to localStorage
every time the user makes an update, we donāt really need to save so frequently.
Why? Because React keeps track of the state
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 localStorage.setItem()
wherever the state
is updated.
So rather than continuously keeping localStorage
in-sync with React state
, letās simply save state
to localStorage
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ā¦
- The user visits the app (localhost:3000 in our case)
- The
App
component mounts and hydrates itsstate
with any applicablelocalStorage
values. - React will update
state
throughout the userās session._localStorage_
wonāt change. - When the user ends their session, save whatever the
state
is at that time tolocalStorage
, making it available for hydrating in the next session.
Alright, hereās a new method for saving all of state
to localStorage
at once. Add it to your App
component.
In order to save state
to localStorage
when the user leaves the app, we need to invoke the saveStateToLocalStorage
method in componentWillUnmount
.
CAVEATāāā**componentWillUnmount**
does not fire when the user refreshes or leaves the page, so we need to utilize the [**window.onbeforeunload**](https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload)
event to be able to save to **localStorage**
. Learn more here.
Hereās some updated code, where we add the event listener to componentDidMount
as well as add what we need to componentWillUnmount
.
We no longer need to setItem
when updating React state
, so youāll want to remove those.
A lot has changed since the beginning of the tutorial, so hereās the App.js
file at this point. *Nothing in the _render()_
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
react-simple-storage_Simple component and helper functions for using localStorage with React._www.npmjs.com
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
yarn add react-simple-storage
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 App.js
using react-simple-storage looks like thisā¦
ryanjyost/react-simple-storage_react-simple-storage - Simple component and helper functions for using localStorage with React._github.com