lotsoftools

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.