Example of useLocalStorage() Custom hook in React.js

Example of useLocalStorage() Custom hook in React.js

Here's how to make a useLocalStorage() hook in React, so you can keep state saved in the browser's local storage:

import { useState } from 'react';

const useLocalStorage = (key, initialValue) => {
  // Get initial value from local storage if available, otherwise use initialValue
  const [storedValue, setStoredValue] = useState(() => {
    try {
      const item = window.localStorage.getItem(key);
      return item ? JSON.parse(item) : initialValue;
    } catch (error) {
      // Handle errors gracefully
      console.error('Error accessing local storage:', error);
      return initialValue;
    }
  });

  // Update local storage value when state changes
  const setValue = (value) => {
    try {
      // Allow value to be a function to update state based on previous value
      const valueToStore = value instanceof Function ? value(storedValue) : value;
      // Save state to local storage
      setStoredValue(valueToStore);
      window.localStorage.setItem(key, JSON.stringify(valueToStore));
    } catch (error) {
      // Handle errors gracefully
      console.error('Error accessing local storage:', error);
    }
  };

  return [storedValue, setValue];
};

export default useLocalStorage;

You can use this useLocalStorage hook in your components to persist state in local storage. Here's how you can use it:

import React from 'react';
import useLocalStorage from './useLocalStorage'; // Assuming you've placed the hook in a separate file

const MyComponent = () => {
  // State to hold the value stored in local storage
  const [count, setCount] = useLocalStorage('count', 0);

  // Increment count when button is clicked
  const increment = () => {
    setCount(count + 1);
  };

  return (
    <div>
      <h1>Local Storage Example</h1>
      <p>Count: {count}</p>
      <button onClick={increment}>Increment</button>
    </div>
  );
};

export default MyComponent;

In this example:

  • We create the MyComponent functional component.

  • We use the useLocalStorage hook to make a state variable count that stays in local storage under the key 'count'.

  • When the component loads, it gets the stored value from local storage and sets count to this value. If there's no value, it starts at 0.

  • We make an increment function to change the count state variable. Clicking the button increases count, and the updated value is saved in local storage.

Did you find this article valuable?

Support LingarajTechhub All About Programming by becoming a sponsor. Any amount is appreciated!