Home > Web Front-end > JS Tutorial > Managing Local Storage in React with useLocalStorage Hook

Managing Local Storage in React with useLocalStorage Hook

Susan Sarandon
Release: 2025-01-27 02:44:37
Original
204 people have browsed it

Managing Local Storage in React with useLocalStorage Hook

This article demonstrates building a reusable useLocalStorage React hook for efficient local storage management. This simplifies persistent data handling in your React applications, offering a clean and type-safe approach.

1. Local Storage Utility Functions

Before creating the hook, we build helper functions for interacting with localStorage:

  • setItem(key: string, value: unknown): Safely stores data in localStorage. It serializes the value using JSON.stringify and handles potential errors (like exceeding storage limits) by logging them to the console.

  • getItem<T>(key: string): T | undefined: Retrieves and parses data from localStorage. It uses TypeScript generics (<T>) for type safety, returning undefined if the key doesn't exist. Error handling is included.

  • removeItem(key: string): Removes a key-value pair from localStorage, also with error handling.

2. The useLocalStorage Hook

The core of this solution is the useLocalStorage hook:

  • Initialization: The hook takes a key (for localStorage) and an initialValue as parameters. It initializes its state using useState, checking localStorage for existing data; if not found, it uses initialValue.

  • State Updates (handleDispatch): This function updates both the component's state and localStorage. It accepts either a new value or a function (for updating based on the previous state), ensuring synchronization.

  • State Clearing (clearState): This function resets the state to undefined and removes the item from localStorage.

  • Return Value: The hook returns an array: [value, handleDispatch, clearState], providing access to the current value, the update function, and the clear function.

3. Using the Hook

Here's how to use useLocalStorage in a React component:

import useLocalStorage from "./useLocalStorage"; // Path to your hook file

function Counter() {
  const [count, setCount, clearCount] = useLocalStorage<number>("counter", 0);

  return (
    <div>
      <h1>Counter: {count}</h1>
      <button onClick={() => setCount((prev) => prev + 1)}>Increment</button>
      <button onClick={() => setCount((prev) => prev - 1)}>Decrement</button>
      <button onClick={clearCount}>Reset</button>
    </div>
  );
}
Copy after login

This example demonstrates persistent counter functionality. The count value is stored in localStorage and survives page reloads.

Full Code (localStorage.ts and useLocalStorage.ts)

The complete code for localStorage.ts and useLocalStorage.ts is provided in the original input and remains unchanged.

Conclusion

This custom hook provides a robust, type-safe, and reusable solution for managing persistent data in React applications using localStorage. Its clean API simplifies development and improves code maintainability.

The above is the detailed content of Managing Local Storage in React with useLocalStorage Hook. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template