How to create a custom hook for handling browser storage (localStorage/sessionStorage) in React



Image not found!!

Creating a custom hook for handling browser storage in React, specifically localStorage or sessionStorage, involves encapsulating the logic for reading from and writing to browser storage within a reusable hook. Here's how you can implement it:

javascript
import { useState } from 'react'; const useLocalStorage = (key, initialValue) => { // Retrieve the initial value from localStorage if it exists, otherwise use the initialValue const [storedValue, setStoredValue] = useState(() => { try { const item = window.localStorage.getItem(key); return item ? JSON.parse(item) : initialValue; } catch (error) { console.error('Error retrieving data from localStorage:', error); return initialValue; } }); // Update the localStorage value when the storedValue changes 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 saving data to localStorage:', error); } }; return [storedValue, setValue]; }; export default useLocalStorage;

Usage example:

javascript
import React from 'react'; import useLocalStorage from './useLocalStorage'; const App = () => { // Using useLocalStorage hook const [name, setName] = useLocalStorage('name', 'John'); return ( <div> <input type="text" value={name} onChange={(e) => setName(e.target.value)} /> <p>Hello, {name}!</p> </div> ); }; export default App;

In this custom hook:

  • useLocalStorage takes two arguments: key (the key under which the value will be stored in localStorage) and initialValue (the default value if the key does not exist in localStorage).
  • It initializes the state with the value from localStorage or the initialValue if the key doesn't exist.
  • It provides a setValue function to update the state and persist the new value to localStorage.
  • It returns the current value and the setValue function, mirroring the API of useState.

You can follow a similar pattern for sessionStorage by replacing localStorage with sessionStorage in the hook.