Storage Custom Hooks

Create reusable storage hooks

AdvancedTopic: LocalStorage/SessionStorage
Back

JavaScript Storage Custom Hooks Program

This program helps you to learn the fundamental structure and syntax of JavaScript programming.

Try This Code
// Method 1: useLocalStorage hook (React-like)
function useLocalStorage(key, initialValue) {
    const [storedValue, setStoredValue] = (function() {
        try {
            const item = window.localStorage.getItem(key);
            return item ? JSON.parse(item) : initialValue;
        } catch (error) {
            return initialValue;
        }
    })();
    
    const setValue = function(value) {
        try {
            setStoredValue(value);
            window.localStorage.setItem(key, JSON.stringify(value));
        } catch (error) {
            console.error('Error setting localStorage:', error);
        }
    };
    
    return [storedValue, setValue];
}

// Usage
const [name, setName] = useLocalStorage('name', '');
setName('John');
console.log('Name:', name);

// Method 2: useSessionStorage hook
function useSessionStorage(key, initialValue) {
    const [storedValue, setStoredValue] = (function() {
        try {
            const item = window.sessionStorage.getItem(key);
            return item ? JSON.parse(item) : initialValue;
        } catch (error) {
            return initialValue;
        }
    })();
    
    const setValue = function(value) {
        try {
            setStoredValue(value);
            window.sessionStorage.setItem(key, JSON.stringify(value));
        } catch (error) {
            console.error('Error setting sessionStorage:', error);
        }
    };
    
    return [storedValue, setValue];
}

// Method 3: useStorage with options
function useStorage(key, initialValue, options = {}) {
    const storage = options.storage || localStorage;
    const serializer = options.serializer || JSON;
    
    const [storedValue, setStoredValue] = (function() {
        try {
            const item = storage.getItem(key);
            return item ? serializer.parse(item) : initialValue;
        } catch (error) {
            return initialValue;
        }
    })();
    
    const setValue = function(value) {
        try {
            setStoredValue(value);
            storage.setItem(key, serializer.stringify(value));
        } catch (error) {
            console.error('Storage error:', error);
        }
    };
    
    const removeValue = function() {
        try {
            storage.removeItem(key);
            setStoredValue(initialValue);
        } catch (error) {
            console.error('Remove error:', error);
        }
    };
    
    return [storedValue, setValue, removeValue];
}

// Method 4: Storage hook with expiration
function useStorageWithExpiry(key, initialValue, ttl) {
    const [storedValue, setStoredValue] = (function() {
        try {
            const item = localStorage.getItem(key);
            if (!item) return initialValue;
            
            const parsed = JSON.parse(item);
            if (Date.now() > parsed.expiry) {
                localStorage.removeItem(key);
                return initialValue;
            }
            
            return parsed.value;
        } catch (error) {
            return initialValue;
        }
    })();
    
    const setValue = function(value) {
        try {
            const item = {
                value: value,
                expiry: Date.now() + ttl
            };
            setStoredValue(value);
            localStorage.setItem(key, JSON.stringify(item));
        } catch (error) {
            console.error('Storage error:', error);
        }
    };
    
    return [storedValue, setValue];
}

// Method 5: Storage hook with sync
function useSyncedStorage(key, initialValue) {
    const [storedValue, setStoredValue] = (function() {
        try {
            const item = localStorage.getItem(key);
            return item ? JSON.parse(item) : initialValue;
        } catch (error) {
            return initialValue;
        }
    })();
    
    // Listen for changes from other tabs
    window.addEventListener('storage', function(e) {
        if (e.key === key) {
            setStoredValue(JSON.parse(e.newValue));
        }
    });
    
    const setValue = function(value) {
        try {
            setStoredValue(value);
            localStorage.setItem(key, JSON.stringify(value));
        } catch (error) {
            console.error('Storage error:', error);
        }
    };
    
    return [storedValue, setValue];
}
Output
Name: John

Understanding Storage Custom Hooks

Custom hooks simplify storage usage.

Hook Pattern

Encapsulate logic
Provide simple API
Handle errors
Return values and setters

Hook Types

useLocalStorage
useSessionStorage
useStorage (generic)
useStorageWithExpiry
useSyncedStorage

Benefits

Reusable
Consistent API
Error handling
Type safety

Use Cases

React components
State management
User preferences
Form data

Best Practices

Handle errors
Provide defaults
Support options
Document usage

Let us now understand every line and the components of the above program.

Note: To write and run JavaScript programs, you need to set up the local environment on your computer. Refer to the complete article Setting up JavaScript Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your JavaScript programs.

Practical Learning Notes for Storage Custom Hooks

This JavaScript program is part of the "LocalStorage/SessionStorage" topic and is designed to help you build real problem-solving confidence, not just memorize syntax. Start by understanding the goal of the program in plain language, then trace the logic line by line with a custom input of your own. Once you can predict the output before running the code, your understanding becomes much stronger.

A reliable practice pattern is to run the original version first, then modify only one condition or variable at a time. Observe how that single change affects control flow and output. This deliberate style helps you understand loops, conditions, and data movement much faster than copying full solutions repeatedly.

For interview preparation, explain this solution in three layers: the high-level approach, the step-by-step execution, and the time-space tradeoff. If you can teach these three layers clearly, you are ready to solve close variations of this problem under time pressure.

Table of Contents