DEV Community

Cover image for Using the Local Storage API in React: Creating a custom hook component
Michael Osas
Michael Osas

Posted on

Using the Local Storage API in React: Creating a custom hook component

As you browse the web, you might have noticed that some websites remember your preferences or settings even after you close your browser or turn off your device. This is possible because of the localStorage API, a feature of web browsers that allows developers to store data in a user's browser.

What is localStorage API?

In simple terms, it's a way for web developers to store information on a user's browser that's specific to a particular website or web application. It's like a digital notebook that remembers your preferences, settings, and other types of data that you want to keep for future reference.

Once data is stored using the localStorage API, it stays there until it's explicitly removed. This means that even if you close your browser, shut down your device, or come back to the website at a later time, the data will still be there. For example, if you're shopping online and add items to your cart, the website can use the localStorage API to remember the items even if you navigate away from the page or close your browser.

The localStorage API is part of the Web Storage API specification, which also includes the sessionStorage API. The difference between the two is that localStorage is designed to store data indefinitely, while sessionStorage only stores data for the duration of a single browsing session. So, if you close your browser or navigate away from the website, the data stored in sessionStorage will be lost.

Why local storage should be used in your project?

local storage can be a useful tool for improving the functionality, performance, and security of your web application, as well as enhancing the user experience. Here are some reasons why you might want to use local storage in your project:

1. Offline Functionality: Local storage can be used to store data locally on the user's device, which allows the application to work even when the user is offline.

2. Performance Improvement: By storing data locally, the application can reduce the number of network requests needed, resulting in a faster and more responsive application.

3. User Experience: Local storage can be used to remember user preferences or settings, such as language selection, preferred theme, or other customizations, which can improve the overall user experience.

4. Security: Unlike cookies, which can be accessed by both the client and the server, data stored in local storage is only accessible by the client, making it a more secure option for storing sensitive data.

5. Scalability: Local storage can handle large amounts of data, and it is relatively easy to use and implement, making it a scalable solution for storing application data.

How to make a localStorage hook component?

To use the localStorage API, web developers can write JavaScript code that calls methods like setItem, getItem, removeItem, and clear. These methods are used to add, retrieve, delete, and clear data from the localStorage object. However, it's important to note that localStorage is limited by the amount of storage space available in the user's browser, which is typically around 5-10 MB.

Create a react component useLocalStorage.jsx

To create a custom hook wrapper component, we'll need to create a component with the file name "useLocalStorage". Here's the complete code for the custom hook, which we'll go through step by step to explain what each function does.

import { useState } from 'react';

export default function useLocalStorage(key, initialValue) {
  const [storedValue, setStoredValue] = useState(() => {
    try {
      const item = window.localStorage.getItem(key);
      return item ? JSON.parse(item) : initialValue;
    } catch (error) {
      console.error(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);
    }
  };

  const removeValue = () => {
    try {
      setStoredValue(null);
      window.localStorage.removeItem(key);
    } catch (error) {
      console.error(error);
    }
  };

  return [storedValue, setValue, removeValue];
}

```


 The provided code demonstrates a useful approach for persisting data within a React application using the `localStorage` API. Specifically, the code defines a custom hook called `useLocalStorage` which takes in a key (to identify the value in `localStorage`) and an initial value. This hook returns an array containing the current value and a function to update it.

The hook takes two parameters: key, which is a string that identifies the data being stored, and initialValue, which is the default value for the data in case it is not yet present in the localStorage.

The useState hook is used to define the storedValue state variable, which is initialized with the value of the key in localStorage if it exists, or with the initialValue if it does not. The hook also defines the setStoredValue function, which is used to update the value of storedValue in both the component's state and the localStorage.

The `setValue` function is defined as a wrapper around `setStoredValue`, with additional logic that handles updating the `localStorage`. If the value passed to `setValue` is a function, it is called with the current value of `storedValue` as its argument. Otherwise, the value is used directly. The `valueToStore` variable is then set to the result of the function call or the value itself. The new value of `storedValue` is set with `setStoredValue`, and the `valueToStore` is stored in the `localStorage`.

The `removeValue` function is defined to remove the value from the `localStorage`. It sets the value of `storedValue` to null and removes the item from the `localStorage`.

Finally, the hook returns an array of `[storedValue, setValue, removeValue]`, which can be used to access and manipulate the stored value. The first element of the array is the current value of `storedValue`, the second element is the `setValue` function, and the third element is the `removeValue` function. This allows the component to get, set, and remove the data from `localStorage` using a simple and standardized interface.


Create another component named RandomComponent (name it whatever you want), this component will use the custom hook we just created



````Javascript

import useLocalStorage from "./useLocalStorage";

export default function RandomComponent() {
  const [count, setCount, clearCount] = useLocalStorage("coun", 0);

  const incrementCount = () => {
    setCount(count + 1);
  };

  const decrementCount = () => {
    setCount(count - 1);
  };

  return (
    <div>
      <h1>Count: {count}</h1>
      <button onClick={incrementCount}>Increment</button>
      <button onClick={decrementCount}>Decrement</button>
    </div>
  );
}
```
{% endraw %}

This is a React component called {% raw %}`RandomComponent`{% endraw %} that uses a custom hook called {% raw %}`useLocalStorage`{% endraw %} to store and retrieve a count value in the browser's {% raw %}`localStorage`. The `useLocalStorage` hook takes in two arguments, the key "count" and the default value 0, and returns an array with three elements: the current count value, a function to update the count value and store it in `localStorage`, and a function to remove the count value from `localStorage`.

In the component's return statement, the current count value is displayed along with two buttons that call the {% raw %}`incrementCount`{% endraw %} and {% raw %}`decrementCount`{% endraw %} functions when clicked. These functions use the {% raw %}`setCount`{% endraw %} function returned from the {% raw %}`useLocalStorage`{% endraw %} hook to update the value of count and store it in {% raw %}`localStorage`{% endraw %}. The component retrieves the count value from {% raw %}`localStorage`{% endraw %} when it mounts or updates, ensuring that the count value is persisted across page refreshes and navigations.



**My final thoughts...**

The localStorage API is a useful tool for web developers who want to create personalized user experiences and store data locally in a user's browser. By using this feature, websites can remember your preferences, settings, and other types of data, making your browsing experience more convenient and enjoyable.
Enter fullscreen mode Exit fullscreen mode

Top comments (0)