Lesson 6 of 8
Custom Hooks - Logic Sharing
Custom hooks are the primary tool for code reuse in modern React - they replace both HOCs and render props for sharing stateful behavior. A well-designed custom hook encapsulates one concern completely, with a clean API that hides complexity.
Production Custom Hook Library
import { useState, useEffect, useCallback, useRef, useLayoutEffect } from 'react';
// useMediaQuery - responsive at the hook level
function useMediaQuery(query: string): boolean {
const [matches, setMatches] = useState(() => {
if (typeof window === 'undefined') return false; // SSR safe
return window.matchMedia(query).matches;
});
useEffect(() => {
const mql = window.matchMedia(query);
const handler = (e: MediaQueryListEvent) => setMatches(e.matches);
mql.addEventListener('change', handler);
return () => mql.removeEventListener('change', handler);
}, [query]);
return matches;
}
// Usage
const isMobile = useMediaQuery('(max-width: 768px)');
const prefersReducedMotion = useMediaQuery('(prefers-reduced-motion: reduce)');
// useLocalStorage - persistent state
function useLocalStorage<T>(key: string, initialValue: T) {
const [storedValue, setStoredValue] = useState<T>(() => {
try {
const item = localStorage.getItem(key);
return item ? JSON.parse(item) : initialValue;
} catch { return initialValue; }
});
const setValue = useCallback((value: T | ((prev: T) => T)) => {
try {
const valueToStore = value instanceof Function ? value(storedValue) : value;
setStoredValue(valueToStore);
localStorage.setItem(key, JSON.stringify(valueToStore));
} catch { /* silent fail */ }
}, [key, storedValue]);
return [storedValue, setValue] as const;
}
// usePrevious - access previous render's value
function usePrevious<T>(value: T): T | undefined {
const ref = useRef<T | undefined>(undefined);
useEffect(() => { ref.current = value; }); // no deps - runs after every render
return ref.current;
}
// useMeasure - get DOM element dimensions
function useMeasure<T extends HTMLElement>() {
const ref = useRef<T>(null);
const [dimensions, setDimensions] = useState({ width: 0, height: 0 });
useLayoutEffect(() => {
if (!ref.current) return;
const observer = new ResizeObserver(([entry]) => {
const { width, height } = entry.contentRect;
setDimensions({ width, height });
});
observer.observe(ref.current);
return () => observer.disconnect();
}, []);
return [ref, dimensions] as const;
}
// useEventListener - safely add event listeners
function useEventListener<K extends keyof WindowEventMap>(
eventName: K,
handler: (event: WindowEventMap[K]) => void,
element: Window | HTMLElement = window,
options?: boolean | AddEventListenerOptions
) {
const savedHandler = useRef(handler);
useEffect(() => { savedHandler.current = handler; });
useEffect(() => {
const listener = (event: Event) => savedHandler.current(event as WindowEventMap[K]);
element.addEventListener(eventName, listener, options);
return () => element.removeEventListener(eventName, listener, options);
}, [eventName, element, options]);
}
// Usage
useEventListener('scroll', () => setScrolled(window.scrollY > 100));Tip
Tip
Practice Custom Hooks Logic Sharing in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Visual architecture and flow for Custom Hooks - Logic Sharing
Practice Task
Note
Practice Task - (1) Write a working example of Custom Hooks Logic Sharing from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with Custom Hooks Logic Sharing is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready react code.
Finished this lesson?