Storage

With web storage, web applications can store data locally within the user's browser.

useLocalStorage

Sync state to local storage so that it persists through a page refresh. Usage is similar to useState except we pass in a local storage key so that we can default to that value on page load instead of the specified initial value.

Usage

import React from 'react';
import useLocalStorage from '@/hooks/storage/useLocalStorage';

// Usage
function App() {
  // Similar to useState but first arg is key to the value in local storage.
  const [name, setName] = useLocalStorage("name", "Bob");
  return (
    <div>
      <input
        type="text"
        placeholder="Enter your name"
        value={name}
        onChange={(e) => setName(e.target.value)}
      />
    </div>
  );
};

useSessionStorage

Sync state to session storage so that it persists through a page refresh. Usage is similar to useState except we pass in a local storage key so that we can default to that value on page load instead of the specified initial value.

Usage

import React from 'react';
import useSessionStorage from '@/hooks/storage/useSessionStorage';

// Usage
function App() {
  // Similar to useState but first arg is key to the value in session storage.
  const [name, setName] = useSessionStorage("name", "Bob");
  return (
    <div>
      <input
        type="text"
        placeholder="Enter your name"
        value={name}
        onChange={(e) => setName(e.target.value)}
      />
    </div>
  );
};

Last updated

Was this helpful?