React Custom Hooks

The primary purpose of the provided custom React Hook, useLocalStorageState, is to adhere to the DRY (Don't Repeat Yourself) principle by encapsulating the logic for managing state and synchronizing it with local storage. This ensures that developers can reuse this functionality across multiple components without duplicating code, thereby promoting cleaner and more maintainable codebases.

Declaration of Hook

import React, { useState, useEffect, useRef } from "react";

function useLocalStorageState(
  key,
  defaultValue = '',
  { serialize = JSON.stringify, deserialize = JSON.parse } = {},
) {
  // Initialize state with local storage value (if available) or default value
  const [state, setState] = useState(() => {
    const valueInLocalStorage = window.localStorage.getItem(key);
    if (valueInLocalStorage) {
      return deserialize(valueInLocalStorage);
    }
    // If default value is a function, execute it, else return default value
    return typeof defaultValue === 'function' ? defaultValue() : defaultValue;
  });

  // Ref to keep track of previous key
  const prevKeyRef = useRef(key);

  // Effect to update local storage when state or key changes
  useEffect(() => {
    // Retrieve previous key
    const prevKey = prevKeyRef.current;
    // If key has changed, remove previous key from local storage
    if (prevKey !== key) {
      window.localStorage.removeItem(prevKey);
    }
    // Update ref with current key
    prevKeyRef.current = key;
    // Set current state to local storage
    window.localStorage.setItem(key, serialize(state));
  }, [key, state, serialize]);

  // Return state and setState function
  return [state, setState];
}

export { useLocalStorageState };

Implementation of Hook

function YourComponentNameWhereYouNeed(props) {
  // This was a sample code from one of my project.
  const [localLogs, setLocalLogs] = useLocalStorageState('localLogs')

   return (
      <div>
         {...}
      </div>
   )

}