Hello! Welcome back to our module on creating reusable logic with custom hooks.
In our last lesson, we transformed our useForm hook into a powerful tool by adding validation and error handling, first with a custom engine and then with the industry-standard library, Zod. This demonstrated how to encapsulate complex logic and integrate third-party libraries to build robust, production-ready hooks.
Today, we're tackling another fundamental challenge in web development: state persistence. The state you've managed with useState so far is ephemeral—it vanishes the moment a user reloads the page. Our learning outcome for this lesson is to create a useLocalStorage hook for persisting state across browser sessions. We'll build a hook that mirrors the familiar useState API but has the superpower of remembering its value.
Understanding the Browser's Memory: localStorage
Before we build our hook, let's briefly look at the tool we'll be using: window.localStorage. It's a simple key-value store built into every modern browser that allows you to save data that persists even after the browser is closed and reopened.
The API is straightforward:
localStorage.setItem('myKey', 'myValue'): Saves a value.localStorage.getItem('myKey'): Retrieves a value.localStorage.removeItem('myKey'): Deletes a value.
There's one crucial detail: localStorage can only store strings. If you want to store an object or an array, you must first convert it to a string using JSON.stringify() and then parse it back with JSON.parse() upon retrieval. This serialization/deserialization process will be a core part of our hook.
Building the useLocalStorage Hook
Our goal is to create a hook that we can use like this:
const [name, setName] = useLocalStorage<string>('username', 'Guest');
This should feel identical to using useState, but the name value will be saved to localStorage and reloaded automatically.
We'll build this hook step-by-step. The following video provides an excellent walkthrough of the core concepts, especially how to combine useState, useEffect, and TypeScript generics to create a flexible and type-safe hook.
Local Storage | Custom React Hook with Typescript
This video, 'Local Storage | Custom React Hook with Typescript' by Weibenfalk, will be our primary guide. It clearly demonstrates the fundamental pattern of reading from localStorage on initialization and writing to it when the state changes.
Please watch from 05:52 to 17:17. As you watch, focus on these four key implementation details: The Hook's Structure (05:52 - 07:57): Notice the signature useLocalStorage(key, initialValue) and how it uses useState and useEffect internally, ultimately returning a [state, setState] pair. TypeScript Generics (07:57 - 12:20): Pay close attention to how <T> is used. This is crucial for making the hook reusable with any data type (string, number, object) while maintaining type safety. Reading from localStorage (12:20 - 15:53): Observe the use of a function inside useState (useState(() => { ... })). This is called lazy initialization, and it's a performance optimization that ensures we only read from localStorage once. Also, note the try-catch block, which is essential for handling cases where localStorage might not be available. Writing to localStorage (15:53 - 17:17): See how useEffect is used with state in its dependency array. This creates a side effect that runs every time the state changes, keeping localStorage in sync.
Synthesizing the Code
Let's combine the principles from the video into a single, well-structured hook. Your software engineering background will appreciate how we are building a robust, reusable component that abstracts away the complexities of the localStorage API.
Here is the complete, annotated code for our useLocalStorage hook.
// src/hooks/useLocalStorage.ts
import { useState, useEffect } from 'react';
// A helper function to safely parse JSON
function safeJsonParse<T>(jsonString: string | null): T | null {
if (jsonString === null) {
return null;
}
try {
return JSON.parse(jsonString) as T;
} catch (e) {
console.error("Failed to parse JSON from localStorage", e);
return null;
}
}
export function useLocalStorage<T>(key: string, initialValue: T): [T, (value: T | ((val: T) => T)) => void] {
// 1. Lazy Initialization with useState
// We pass a function to useState to ensure this complex logic runs only once on initial render.
const [storedValue, setStoredValue] = useState<T>(() => {
// Check if window is defined (for SSR environments)
if (typeof window === 'undefined') {
return initialValue;
}
try {
// Get from local storage by key
const item = window.localStorage.getItem(key);
// Parse stored json or if none return initialValue
const parsedItem = safeJsonParse<T>(item);
return parsedItem !== null ? parsedItem : initialValue;
} catch (error) {
// If error, return initialValue and log the error
console.log(error);
return initialValue;
}
});
// 2. Syncing with localStorage using useEffect
// This effect runs whenever 'storedValue' changes.
useEffect(() => {
// Again, check for SSR
if (typeof window === 'undefined') {
return;
}
try {
// Allow value to be a function so we have same API as useState
const valueToStore = storedValue;
// Save state to local storage
window.localStorage.setItem(key, JSON.stringify(valueToStore));
} catch (error) {
// A more advanced implementation could handle this error case
console.log(error);
}
}, [key, storedValue]);
// We need to match the return type of React's `useState` setter function.
const setValue = (value: T | ((val: T) => T)) => {
try {
const valueToStore = value instanceof Function ? value(storedValue) : value;
setStoredValue(valueToStore);
} catch (error) {
console.log(error);
}
};
return [storedValue, setValue];
}
Test your understanding!
In our useState lazy initializer, we have a try...catch block. Besides JSON parsing errors, what is a common scenario where window.localStorage.getItem(key) itself might throw an error?
Show answer
This can happen if the user has disabled localStorage in their browser settings or is using a privacy-focused browser mode (like Safari's Private Browsing). In such cases, any attempt to access localStorage will throw a security error. The try...catch block gracefully handles this by falling back to the initialValue, preventing the entire application from crashing.
Using Our New Hook
Now, you can use this hook in any component to create state that survives a page refresh. Let's build a simple theme switcher.
// src/components/ThemeSwitcher.tsx
import React from 'react';
import { useLocalStorage } from '../hooks/useLocalStorage';
type Theme = 'light' | 'dark';
export function ThemeSwitcher() {
const [theme, setTheme] = useLocalStorage<Theme>('app-theme', 'light');
const toggleTheme = () => {
setTheme(prevTheme => (prevTheme === 'light' ? 'dark' : 'light'));
};
// Apply the theme to the body for demonstration
React.useEffect(() => {
document.body.style.backgroundColor = theme === 'light' ? '#FFF' : '#282c34';
document.body.style.color = theme === 'light' ? '#000' : '#FFF';
}, [theme]);
return (
<div>
<h1>Current Theme: {theme}</h1>
<button onClick={toggleTheme}>Toggle Theme</button>
<p>Refresh the page. The theme will be remembered!</p>
</div>
);
}
Try this out in your application. You'll see that when you toggle the theme and then refresh the browser, the selected theme persists.
Advanced Considerations
Our hook is already very useful, but for a truly production-grade solution, there are more edge cases to consider. The article "Mastering LocalStorage Management with React Hooks" discusses two of them.
Mastering LocalStorage Management with React Hooks
This article by Ekom Ekrresa provides a very robust implementation of a useLocalStorage hook. We won't implement everything, but we will borrow two key ideas to make our hook even better.
You don't need to read the full article, just skim these two sections to understand the concepts: SSR Compatibility: This section explains why localStorage is problematic for Server-Side Rendering and introduces useLayoutEffect as a solution to read the initial value only on the client. Syncing the value across tabs: This section introduces the browser's native storage event, which allows an application to react to changes made in other tabs.
-
Server-Side Rendering (SSR) Safety: Our current hook checks for
typeof window, which prevents crashes during SSR. However, a more robust solution as seen in the article is to only read fromlocalStorageinside auseEffectoruseLayoutEffect. This prevents hydration mismatches where the server-rendered HTML doesn't match the initial client-rendered HTML.useLayoutEffectis preferred as it runs synchronously before the browser paints, avoiding a visual flicker. -
Syncing Across Tabs: What if a user has your app open in two tabs? If they change the theme in one tab, the other tab won't know. We can fix this by listening to the
storageevent.
Here is how you would add a useEffect to handle cross-tab synchronization:
// Inside your useLocalStorage hook...
useEffect(() => {
const handleStorageChange = (event: StorageEvent) => {
if (event.key === key) {
const newValue = safeJsonParse<T>(event.newValue);
if (newValue !== null) {
setStoredValue(newValue);
}
}
};
window.addEventListener('storage', handleStorageChange);
// Cleanup function to remove the listener when the component unmounts
return () => {
window.removeEventListener('storage', handleStorageChange);
};
}, [key]);
Adding this useEffect to our hook makes it aware of changes happening in other browser tabs, creating a seamless, synchronized experience.
Conclusion
You have now built a powerful and practical useLocalStorage hook, adding another essential utility to your custom hook library. You've seen how to abstract browser APIs into a declarative React pattern, handle edge cases like SSR and error handling, and even synchronize state across browser tabs.
Key Takeaways:
- The Core Pattern:
useLocalStoragecombinesuseState(with lazy initialization) to hold the value in memory anduseEffectto persist that value to the browser'slocalStorage. - Type Safety is Paramount: Using TypeScript generics (
<T>) makes the hook robust and reusable for any serializable data type. - Error Handling is Non-Negotiable:
localStoragecan be unavailable or throw errors.try...catchblocks are essential to prevent your application from crashing. - Advanced Hooks Consider More Context: Production-grade hooks often account for SSR and multi-tab synchronization to provide a flawless user experience.
Preview of the Next Lesson:
We now have a collection of powerful, single-purpose hooks: useFetch, useForm, and useLocalStorage. What happens when we need to combine their powers? In our next and final lesson of this module, we will explore how to compose multiple hooks together to build more complex custom hooks, unlocking even more sophisticated and elegant patterns for managing application logic.