Use of LocalStorage in React Application
In React.js, you can use the browser’s localStorage
API to store data locally within the user’s browser. This allows you to persist data across sessions and page reloads, making it useful for storing user preferences, authentication tokens, or any other data that needs to be preserved between visits to your application.
Here’s how you can use localStorage
in a React application:
- Setting Data:
You can store data inlocalStorage
using thesetItem()
method. This method takes two arguments: a key and a value. The value must be a string.
localStorage.setItem('key', 'value');
- Getting Data:
You can retrieve data fromlocalStorage
using thegetItem()
method. This method takes the key of the item you want to retrieve and returns its value as a string.
const value = localStorage.getItem('key');
- Removing Data:
You can remove data fromlocalStorage
using theremoveItem()
method. This method takes the key of the item you want to remove.
localStorage.removeItem('key');
- Example in React Component:
Here’s an example of how you can uselocalStorage
in a React component to persist and retrieve data:
import React, { useState, useEffect } from 'react';
function MyComponent() {
const [value, setValue] = useState('');
useEffect(() => {
// Retrieve data from localStorage when component mounts
const storedValue = localStorage.getItem('myValue');
if (storedValue) {
setValue(storedValue);
}
}, []);
const handleChange = (event) => {
const newValue = event.target.value;
setValue(newValue);
// Store data in localStorage when value changes
localStorage.setItem('myValue', newValue);
};
return (
<div>
<input type="text" value={value} onChange={handleChange} />
<p>Stored Value: {value}</p>
</div>
);
}
In this example, the component initializes its state with the value stored in localStorage
when it mounts. When the user changes the input value, the component updates its state and stores the new value in localStorage
. This ensures that the input value is persisted between page reloads.