ArticleZip > How To Listen To Localstorage In React Js

How To Listen To Localstorage In React Js

Have you ever wanted to keep track of changes in your React app's local storage and respond to them dynamically? Today, we'll walk you through a simple and effective way to listen to local storage changes in a React JS application. By the end of this guide, you'll be equipped with the necessary knowledge to implement this feature seamlessly in your projects.

The first step is to create a custom hook that will enable us to listen to local storage changes. We'll name this custom hook 'useLocalStorageListener'. Within this hook, we will subscribe to the 'storage' event and check if the changes occurred in the 'localStorage' object.

Jsx

import { useEffect } from 'react';

const useLocalStorageListener = (callback) => {
  useEffect(() => {
    const handleStorageChange = () => {
      if (event.key === 'yourLocalStorageKey') {
        callback(event.newValue);
      }
    };

    window.addEventListener('storage', handleStorageChange);

    return () => {
      window.removeEventListener('storage', handleStorageChange);
    };
  }, [callback]);
};

export default useLocalStorageListener;

In this custom hook, we set up an 'eventListener' for the 'storage' event. Whenever a change occurs in the local storage, the 'handleStorageChange' function is triggered. We then check if the change is relevant to the specific key we are interested in, and if so, we invoke the provided callback function with the updated value.

Now, let's integrate our custom hook into a React component to see how it all comes together.

Jsx

import React, { useState } from 'react';
import useLocalStorageListener from './useLocalStorageListener';

const App = () => {
  const [storageValue, setStorageValue] = useState(localStorage.getItem('yourLocalStorageKey'));

  useLocalStorageListener((value) => {
    setStorageValue(value);
  });

  const handleChange = (e) => {
    const value = e.target.value;
    localStorage.setItem('yourLocalStorageKey', value);
    setStorageValue(value);
  };

  return (
    <div>
      
      <p>Current value in Local Storage: {storageValue}</p>
    </div>
  );
};

export default App;

In this example, we initialize the component state with the value retrieved from the local storage. We then use our custom hook 'useLocalStorageListener' to listen for any changes related to our specified key. Whenever a change is detected, the component state is updated accordingly, ensuring our UI reflects the most recent value stored in the local storage.

By following these steps and leveraging the power of custom hooks in React JS, you can easily implement a mechanism to listen to local storage changes in your applications. This feature adds a layer of interactivity and responsiveness to your app, empowering you to create richer user experiences. So why not give it a try in your next project? Happy coding!