useLocalStorage in React Hook

Chay Auker
2 min readAug 12, 2021

--

What is local storage?

Data can be stored within a browser. There is no expiration date for data stored in the localStorage object. Key/value pairs can be saved within a web browser by using localStorage. Therefore, subsequent closing of the browser will not result in the data being deleted, and it will remain accessable in the future.

  1. Installing with npm as follow:
npm i uselocalstorage-react-hook

2. Add Import useLocalStorage to the application

import useLocalStorage from "uselocalstorage-react-hook";

3. Implement useLocalStorage into the application to create key/value pairs

const [user, setUser] = useLocalStorage("name", "John Doe");

4. As you can see from below code, this input sets the value as “John Doe”. When changing the value, user is set to the value that the user types (e.target.value).

5. The goal is to change the name to “Jason Doe” and check if the local storage changes with it. Go to “Application” → “Local Storage” → “Application’s domain”, you can see Key as “Name” and value as “Jason Doe”

6. It’s time to test if the data is stored in the local storage. Then refresh the page to see if “Jason Doe” is now shown. Tada!!! “Jason Doe” is now stored in local storage.

--

--

Chay Auker
Chay Auker

Written by Chay Auker

Software Engineering at Flatiron

No responses yet