Docs
LocalStorage

LocalStorage

Store, retrieve, and synchronize data from the browser’s localStorage API

About

The useLocalStorage hook synchronizes the state of a component with data stored in local storage. It reads the initial value from local storage when the component mounts and updates the local storage whenever the state changes. It also listens for changes in local storage made by other tabs or windows, keeping the component’s state up to date.

Parameters

NameTypeDescription
keystringThe key used to access the local storage value.
initialValueanyThe initial value to use if there is no item in the local storage with the provided key.

Return Values

NameTypeDescription
localStateanyThe current state of the value stored in local storage.
handleSetStatefunctionA function to set the state of the value in the local storage. This function accepts a new value or a function that returns a new value. The value is also saved in the local storage under the provided key.

Installation

Run the following command:

npx scriptkavi-hooks@latest add local-storage

Usage

import { useLocalStorage } from "@/hooks/local-storage"
import * as React from "react"
 
import createDrawing from "./createDrawing"
 
export default function App() {
  const [drawing, saveDrawing] = useLocalStorage("drawing", null)
  const ref = React.useRef(null)
  React.useEffect(() => {
    createDrawing(ref.current, drawing, saveDrawing)
  }, [drawing, saveDrawing])
 
  return (
    <section>
      <header>
        <h1>useLocalStorage</h1>
 
        <button className="link" onClick={() => window.location.reload()}>
          Reload Window
        </button>
        <button
          className="link"
          onClick={() => {
            window.localStorage.clear()
            window.location.reload()
          }}
        >
          Clear Local Storage
        </button>
      </header>
      <figure>
        <canvas ref={ref} width={800} height={800} />
        <figcaption>(draw something)</figcaption>
      </figure>
    </section>
  )
}