typescriptadvanced
useSelectionRange Hook
Tracks user text selection within a container, returning selected text and range coordinates.
typescriptPress ⌘/Ctrl + Shift + C to copy
import { useState, useEffect, useRef, RefObject } from 'react';
interface Selection {
text: string;
rect: DOMRect | null;
}
export function useSelectionRange<T extends HTMLElement>(): [RefObject<T | null>, Selection] {
const ref = useRef<T | null>(null);
const [selection, setSelection] = useState<Selection>({ text: '', rect: null });
useEffect(() => {
const handler = () => {
const sel = window.getSelection();
if (!sel || sel.isCollapsed || !ref.current) {
setSelection({ text: '', rect: null });
return;
}
const range = sel.getRangeAt(0);
if (ref.current.contains(range.commonAncestorContainer)) {
setSelection({
text: sel.toString(),
rect: range.getBoundingClientRect(),
});
}
};
document.addEventListener('selectionchange', handler);
return () => document.removeEventListener('selectionchange', handler);
}, []);
return [ref, selection];
}Use Cases
- Text annotation tools
- Inline commenting
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
typescriptintermediate
useFetch — Generic Data Fetching Hook
Custom React hook for data fetching with loading, error, and refetch states using the Fetch API.
Best for: API data fetching
#hooks#fetch
typescriptbeginner
useDebounce — Debounced Value Hook
Debounce any rapidly-changing value with a configurable delay. Useful for search inputs and resize handlers.
Best for: Search-as-you-type
#hooks#debounce
typescriptintermediate
useLocalStorage — Persistent State Hook
Sync React state with localStorage including SSR safety, JSON serialization, and cross-tab updates.
Best for: User preferences
#hooks#localstorage
typescriptbeginner
useClickOutside — Outside Click Detection
Detect clicks outside a referenced element to close dropdowns, modals, and popover menus.
Best for: Dropdown menus
#hooks#click-outside