Lesson 10 of 11
Mini Project: Custom Hook Library
Build a production-grade custom hook library - `useWindowSize`, `useMediaQuery`, `usePrevious`, `useIsOnline`. Then wire them together in a responsive dashboard component that reacts to window size, network status, and previous state. This pattern appears in virtually every professional React codebase.
The Hook Library
import { useState, useEffect, useRef, useCallback } from 'react';
// 1. useWindowSize - responsive layouts without CSS breakpoints
interface WindowSize { width: number; height: number; }
function useWindowSize(): WindowSize {
const [size, setSize] = useState<WindowSize>(() => ({
width: typeof window !== 'undefined' ? window.innerWidth : 0,
height: typeof window !== 'undefined' ? window.innerHeight : 0,
}));
useEffect(() => {
function handleResize() {
setSize({ width: window.innerWidth, height: window.innerHeight });
}
window.addEventListener('resize', handleResize, { passive: true });
return () => window.removeEventListener('resize', handleResize);
}, []);
return size;
}
// 2. useMediaQuery - CSS media query in JS
function useMediaQuery(query: string): boolean {
const [matches, setMatches] = useState(false);
useEffect(() => {
const mql = window.matchMedia(query);
setMatches(mql.matches);
const handler = (e: MediaQueryListEvent) => setMatches(e.matches);
mql.addEventListener('change', handler);
return () => mql.removeEventListener('change', handler);
}, [query]);
return matches;
}
// 3. usePrevious - track previous value
function usePrevious<T>(value: T): T | undefined {
const ref = useRef<T | undefined>(undefined);
useEffect(() => { ref.current = value; });
return ref.current;
}
// 4. useIsOnline - network status
function useIsOnline(): boolean {
const [isOnline, setIsOnline] = useState(
typeof navigator !== 'undefined' ? navigator.onLine : true
);
useEffect(() => {
const goOnline = () => setIsOnline(true);
const goOffline = () => setIsOnline(false);
window.addEventListener('online', goOnline);
window.addEventListener('offline', goOffline);
return () => {
window.removeEventListener('online', goOnline);
window.removeEventListener('offline', goOffline);
};
}, []);
return isOnline;
}
// 5. useToggle - boolean state with stable toggle function
function useToggle(initial = false): [boolean, () => void, (v: boolean) => void] {
const [value, setValue] = useState(initial);
const toggle = useCallback(() => setValue(v => !v), []);
return [value, toggle, setValue];
}
// ---- Wiring it all together ----
function ResponsiveDashboard() {
const { width } = useWindowSize();
const isMobile = useMediaQuery('(max-width: 768px)');
const isOnline = useIsOnline();
const [count, setCount] = useState(0);
const prevCount = usePrevious(count);
const [sidebarOpen, toggleSidebar] = useToggle(true);
return (
<div style={{ fontFamily: 'system-ui', background: '#0f172a', minHeight: '100vh', color: 'white', padding: 20 }}>
{!isOnline && (
<div style={{ background: '#ef4444', padding: '8px 16px', borderRadius: 8, marginBottom: 12 }}>
โ ๏ธ You are offline - some features may be unavailable
</div>
)}
<div style={{ display: 'flex', gap: 16 }}>
{!isMobile && sidebarOpen && (
<aside style={{ width: 200, background: '#1e293b', borderRadius: 12, padding: 16 }}>
<nav>
<p style={{ color: '#60a5fa', fontWeight: 700 }}>Navigation</p>
{['Dashboard', 'Analytics', 'Settings'].map(item => (
<div key={item} style={{ padding: '8px 0', color: '#94a3b8', cursor: 'pointer' }}>
{item}
</div>
))}
</nav>
</aside>
)}
<main style={{ flex: 1 }}>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 20 }}>
<h1 style={{ margin: 0, fontSize: isMobile ? 20 : 28 }}>Dashboard</h1>
<div style={{ display: 'flex', gap: 8, fontSize: 13, color: '#94a3b8' }}>
{!isMobile && <button onClick={toggleSidebar} style={{ background: '#334155', border: 'none', color: 'white', padding: '6px 12px', borderRadius: 6, cursor: 'pointer' }}>
{sidebarOpen ? 'โ Hide Sidebar' : 'โ Show Sidebar'}
</button>}
<span>{width}px {isMobile ? '(mobile)' : '(desktop)'}</span>
</div>
</div>
<div style={{ background: '#1e293b', borderRadius: 12, padding: 24 }}>
<p>Count: <strong>{count}</strong></p>
<p style={{ color: '#64748b', fontSize: 13 }}>
Previous: {prevCount ?? 'none'} โ Current: {count}
{prevCount !== undefined && count > prevCount ? ' โ' : prevCount !== undefined ? ' โ' : ''}
</p>
<div style={{ display: 'flex', gap: 8, marginTop: 12 }}>
<button onClick={() => setCount(c => c - 1)} style={{ background: '#475569', border: 'none', color: 'white', padding: '8px 16px', borderRadius: 8, cursor: 'pointer' }}>โ</button>
<button onClick={() => setCount(c => c + 1)} style={{ background: '#229c6b', border: 'none', color: 'white', padding: '8px 16px', borderRadius: 8, cursor: 'pointer' }}>+</button>
</div>
</div>
</main>
</div>
</div>
);
}
export default ResponsiveDashboard;What This Project Demonstrates
- useWindowSize - SSR-safe initialization (`typeof window !== 'undefined'`), passive resize listener, cleanup
- useMediaQuery - CSS media queries in JavaScript, syncing with matchMedia API change events
- usePrevious - using `useRef` side channel to capture previous render's value without causing re-renders
- useIsOnline - browser online/offline API wrapped in a hook with proper event listener cleanup
- useToggle - combining useState with useCallback to return a stable toggle function
- Hook composition - `ResponsiveDashboard` uses 5 hooks together, each doing one thing well
- Conditional rendering based on hook values - UI adapts to screen size, network status, sidebar state
- No prop drilling - hooks provide values directly to the component that needs them
Tip
Tip
Practice Mini Project Custom Hook Library 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 Mini Project: Custom Hook Library
Practice Task
Note
Practice Task - (1) Write a working example of Mini Project Custom Hook Library 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 Mini Project Custom Hook Library is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready react code.
Key Takeaways
- Build a production-grade custom hook library - `useWindowSize`, `useMediaQuery`, `usePrevious`, `useIsOnline`.
- useWindowSize - SSR-safe initialization (`typeof window !== 'undefined'`), passive resize listener, cleanup
- useMediaQuery - CSS media queries in JavaScript, syncing with matchMedia API change events
- usePrevious - using `useRef` side channel to capture previous render's value without causing re-renders
Finished this lesson?