Back to snippets

Local Storage Hook

Snippet Overview

This snippet provides a custom React hook, useLocalStorage, to easily read from and write to local storage in a web application.

Code

import { useState } from 'react'; export const useLocalStorage = (key, initialValue) => { const [storedValue, setStoredValue] = useState(() => { try { const item = window.localStorage.getItem(key); return item ? JSON.parse(item) : initialValue; } catch (error) { console.error('Error fetching from local storage:', error); return initialValue; } }); const setValue = value => { try { const valueToStore = value instanceof Function ? value(storedValue) : value; setStoredValue(valueToStore); window.localStorage.setItem(key, JSON.stringify(valueToStore)); } catch (error) { console.error('Error storing to local storage:', error); } }; return [storedValue, setValue]; };

Usage

  • Import and use the useLocalStorage hook within your React components.
  • Provide a unique key to identify the stored value in local storage.
  • Access the stored value and update it using the setValue function.

Conclusion

The useLocalStorage hook simplifies data management in React applications by providing an easy-to-use interface for interacting with local storage. It enhances the persistence of user data and enables seamless user experiences across sessions.

Disclaimer: This snippet is intended for educational purposes and may require additional validation and error handling for production use.