DEV Community

Hunter Chang
Hunter Chang

Posted on • Updated on • Originally published at codebushi.com

JavaScript Local Storage Introduction

Introduction on how to use JavaScript's window.localStorage by creating a Dark Theme toggle for a simple site. We take a look at how to setItem and getItem from Local Storage.

Key Takeaways:

6:42 - localStorage.setItem() takes two arguments, the first is the Key and the second is the Value. Both Key and Value must be a string. You can see these stored values in the browser's dev tools, under the Application tab.

9:10 - To read from local storage, we use localStorage.getItem() and pass it the original Key that was stored. You will get back the string that was stored with the Key.

11:18 - When reading from local storage, it's a good idea to check if something was returned first, and then proceed with your code.

12:50 - If you're using local storage with React, you can store a React state object. You must first JSON.stringify() the object you want to store, since local storage only works with strings.

14:35 - When reading from local storage, and getting a JSON string, you need to JSON.parse() the Value and turn it back into an object.

15:50 - To use with React, one way is to setItem right after you perform a this.setState(), and you would stringify the object as you pass it into localStorage.setItem(). You can then getItem when you do a componentDidMount and this.setState() to retrieve your React state object from local storage.

If you liked this video, please support it by subscribing to the channel!

You can also visit Code Bushi for more resources on Web Development!

Top comments (0)