A Really Simple Intro to localStorage in React

lauratoddcodes

Laura Todd

Posted on May 9, 2021

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.

💖 💪 🙅 🚩
lauratoddcodes
Laura Todd

Posted on May 9, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related