Day 12: localStorage
It can be infuriating to close a webpage while filling out a form accidentally. We lose all the data already filled and have to start over. We can use localStorage to save our data beyond a single browsing session.
What is localStorage?
It is a property that allows sites and apps to save key-value pairs in a web browser with no expiration date. This means the data stored persists even after the user closes the browser or restarts the computer.
localStorage is a window object property, which makes it a global object that can interact with and manipulate the browser window. It can also be used in combination with other window properties and methods.
Why use localStorage?
This feature is useful for storing small amounts of data, such as user preferences, authentication tokens, or application state, without requiring server-side storage.
Working with localStorage
Accessing Local Storage
In React, we can access the browser's local storage using the localStorage object, which is available globally in the browser's window object.
Storing Data
To store data in local storage, use the setItem method of the localStorage object. This method takes two arguments: a key and a value. Both the key and the value must be strings.
localStorage.setItem('key', 'value');
Retrieving Data
To retrieve data from local storage, use the getItem method of the localStorage object. This method takes the key of the item we want to retrieve and returns its corresponding value.
const value = localStorage.getItem('key');
Updating Data
To update data in local storage, we can overwrite the existing key-value pair with a new one using the setItem method.
localStorage.setItem('key', 'new value');
Removing Data
To remove data from local storage, use the removeItem method of the localStorage object. This method takes the key of the item we want to remove.
localStorage.removeItem('key');
Clearing Local Storage
If you want to remove all data from local storage, use the clear method of the localStorage object.
localStorage.clear();
Using Local Storage in React Components
We can use local storage in our React components to persist state or save user preferences. For example, we can store the state of a form input field so that it persists even after the user refreshes the page.
import React, { useState, useEffect } from 'react';
const MyComponent = () => {
// Initializing state with value from local storage or a default value
const [value, setValue] = useState(localStorage.getItem('key') || '');
// Update local storage whenever the state changes
useEffect(() => {
localStorage.setItem('key', value);
}, [value]);
return (
<input
type="text"
value={value}
onChange={(e) => setValue(e.target.value)}
/>
);
};
export default MyComponent;
Thanks to our mentor, Bikash Karki .