Rehooks
Content

useLocalStorage

A hook that manages a state variable in sync with local storage, allowing data persistence across browser sessions.

useLocalStorage

Usage

Component.tsx
import { useLocalStorage } from "~/hooks/useLocalStorage";
import React from "react";
 
function Component() {
  const [name, setName] = useLocalStorage("name", "John Doe");
 
  const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setName(event.target.value);
  };
 
  return (
    <div>
      <h2>Local Storage Demo</h2>
      <input
        type="text"
        value={name}
        onChange={handleChange}
        placeholder="Enter your name"
      />
      <p>Your name is: {name}</p>
    </div>
  );
}

API

useLocalStorage

function useLocalStorage<T>(
  key: string,
  initialValue: T,
): [T, (value: T) => void];

Parameters

NameTypeDescription
keystringThe key for the local storage item.
initialValueTThe initial value for the state variable.

Returns

NameTypeDescription
storedValueTThe current value synchronized with local storage.
setValue(value: T) => voidA function to update the state and sync it with local storage.

On this page