- JSON Formatter/Viewer
Format, minify, visualize and validate JSON.
- JSON Diff
Compare two JSON objects.
- JSON Schema Validator
Validate JSON schema online
- Base64 Encode/Decode
Encode and decode Base64.
- URL Encode/Decode
Encode and decode URL.
- UUID Generator v4 / v1
Generate UUIDs in v4 and other versions.
- Text Hash
Generate cryptographic hashes from your text input using a wide variety of algorithms.
- File Hash
Generate cryptographic hashes from your file using a wide variety of algorithms.
- JWT Decoder & Validator
Decode and validate JSON Web Tokens.
- CSV Viewer
View CSV data in a table.
- CSV to JSON Converter
Convert CSV to JSON.
- JSON to CSV Converter
Convert JSON to CSV.
UseLocalStorage
Explore how to optimally use LocalStorage in programming, including storing, retrieving, and deleting data.
function useLocalStorage(key, initialValue) {
const [storedValue, setStoredValue] = React.useState(() => {
try {
const item = window.localStorage.getItem(key);
return item ? JSON.parse(item) : initialValue;
} catch (error) {
return initialValue;
}
});
const setValue = value => {
try {
const valueToStore = value instanceof Function ? value(storedValue) : value;
setStoredValue(valueToStore);
window.localStorage.setItem(key, JSON.stringify(valueToStore));
} catch (error) {
console.error(error);
}
};
return [storedValue, setValue];
}
This JavaScript function, 'useLocalStorage', is an excellent example of how to implement localStorage. It takes two parameters - a key and an initial value.
The useState React hook is used here to create and manage state corresponding to the stored value. The state is initially set to the value corresponding to the provided key in localStorage. If that doesn't exist, the initial value is used.
The function also comprises an additional function, 'setValue', that allows the stored value to be updated. It sets the new value to localStorage and updates the local state as well.
Whether you're storing user preferences or caching data for offline availability, localStorage is an efficient technique.