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 -
You can find the starting code here.
Add onChange and onSubmit event listeners to the input fields and the form as would normally.
In the constructor, initialise the state for 'name' and 'username'.
Then, create the onChange handler functions, allowing them to set the state of 'name' and 'username' to the input values.
Next, create the onSubmit 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.
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.
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.