A React hook that synchronizes state with localStorage.

This hook reads a value from localStorage using the provided key and uses it as the initial state. It returns a tuple containing the current stored value, a function to update the value (which also updates localStorage), and a function to remove the value from localStorage.

import { useLocalStorage } from "essential-hooks-collection";

const MyComponent = () => {
const [name, setName, removeName] = useLocalStorage("name", "Guest");

return (
<div>
<p>Name: {name}</p>
<button onClick={() => setName("Alice")}>Set to Alice</button>
<button onClick={removeName}>Remove Name</button>
</div>
);
};

export default MyComponent;
  • Type Parameters

    • T

      The type of the stored value.

    Parameters

    • key: string

      The localStorage key under which the value is stored.

    • initialValue: T

      The initial value to use if no data is found in localStorage.

    Returns readonly [T, Dispatch<SetStateAction<T>>, () => void]

    A tuple with:

    • The stored value.
    • A function to update the stored value.
    • A function to remove the value from localStorage.