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.
Top comments (3)
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. 🙌🙌
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.Great article, I take full advantage of this on this custom react hook, to avoid using redux
npmjs.com/package/@dannyman/use-store