DEV Community

Cover image for A Really Simple Intro to localStorage in React
Laura Todd
Laura Todd

Posted on

A Really Simple Intro to localStorage in React

Saving information to local storage can be incredibly useful and can make for a far better user experience in your apps. Imagine if you had to log in from scratch every time you wanted to look at Twitter!

By using the localStorage method in React, we can make save certain information to the user's machine to save them re-entering it whenever they use our app.

I'll take you through a very simple example of saving a name and username from a form.

We'll begin with two input fields and a submit button, like so -

Name and username input fields

You can find the starting code here.

Add onChange and onSubmit event listeners to the input fields and the form as would normally.

Form with input fields and submit button

In the constructor, initialise the state for 'name' and 'username'.

initialisation of name and username

Then, create the onChange handler functions, allowing them to set the state of 'name' and 'username' to the input values.

handler functions

Next, create the onSubmit handler function.

submit handler function

In the first line, we use a destructured array to assign this.state.name and this.state.username to the 'name' and 'username' variables. Then, we use the localStorage.setItem() method store those values as 'name' and 'username' to be accessed by the local storage later.

Make sure that you bind all three functions in the constructor.

Bind functions

Finally, we can use the localStorage.getItem() method within ComponentDidMount() to access the stored values and assign them to this.state.name and this.state.username on initialisation.

component did mount

That's it! Now, when you enter values into the input fields and refresh the page, those values should remain in the fields.

You can check your finished code here.

Discussion (3)

Collapse
nithish_13 profile image
Nithish Kumar

Instead of handling changes for name and username seperately, you can simply do like this,
handleChange = evt => {
this.setState({ [evt.target.name] : evt.target.value })
} and add name attribute of value matching the value of this.state.name || .username. in the respective input fields.

So that the code looks cleaner. Also, the values from the localstorage, always remains the first set of values provided by the user. It would be nice to store recent set of values to the localstorage.
Btw, thanks for the post. 🙌🙌

Collapse
robvirtuoso profile image
robvirtuoso

Would be good to enclose any code that has reference to localStorage in a try-catch block in case some browser misbehaves in its private browsing mode, e.g. previous versions of Safari.

Collapse
dannyfallas profile image
Danny Fallas

Great article, I take full advantage of this on this custom react hook, to avoid using redux
npmjs.com/package/@dannyman/use-store