Skip to Content
UI KitHooksuseLocalStorage

Overview

The useLocalStorage hook offers a simple and efficient way to interact with local storage in React applications. It is designed to store, retrieve, and remove values from local storage with ease, handling serialization and deserialization of data seamlessly.

By incorporating useLocalStorage in your React applications, you can efficiently manage local storage data, ensuring a seamless and responsive user experience.

Key Features

  • Simple Data Storage: Streamlines the process of storing data in local storage.
  • Automatic Serialization: Handles the serialization and deserialization of stored values, supporting both raw string values and JSON objects.
  • Customizable: Offers options for custom serialization and deserialization methods.

How It Works

The hook accepts a storage key, an initial value, and optional parser options for custom serialization. It provides a stateful value, a setter function to update the value, and a function to remove the value from local storage.

Syntax

const [storedValue, setStoredValue, removeStoredValue] = useLocalStorage( key, initialValue, options );
  • key: The key under which to store the value in local storage.
  • initialValue: The initial value to be stored, used if no value is already present.
  • options: Optional configuration for custom serialization and deserialization. If raw is true, the hook treats values as strings. If the options parameter is not used, JSON.stringify()/JSON.parse() is used.
options: { raw: true; } // or options: { raw: false; serializer: (param) => { ... }; // string return value deserializer: (param) => { ... }; // string param value }

Usage Example

Here’s an example demonstrating how to use the useLocalStorage hook in a component:

import { useLocalStorage } from '@akinon/ui-hooks'; const MyComponent = () => { const [name, setName, removeName] = useLocalStorage('name', 'Initial Name'); const updateName = () => { setName('Updated Name'); }; const clearName = () => { removeName(); }; return ( <div> <p>Name: {name}</p> <button onClick={updateName}>Update Name</button> <button onClick={clearName}>Clear Name</button> </div> ); }; export default MyComponent;