useTextSelection
Track current text selection.
Import
TypeScript
import { useTextSelection } from '@/hooks';API
Signature
useTextSelection() → { text, rect, clear }
When to use
Use useTextSelection instead of re-implementing the same pattern in multiple components.
SSR / Next.js
Browser utilities are SSR-gated; lifecycle hooks are safe.
Live playground
Edit the example and see it run against the real @/hooks package in this app.
Live playgroundEdit · run with real
@/hooks · useTextSelectionEditor
function SelectionToolbar() { const { text, clear } = useTextSelection(); if (!text) return null; return ( <div> Selected: {text} <button onClick={clear}>Clear</button> </div> ); }
Preview
Implementation source
Full library source for useTextSelection — copy into your project when you are not installing a package yet.
hooks/utility/useTextSelection.ts
import { useCallback, useEffect, useState } from 'react';
import { isBrowser } from './isBrowser';
export interface TextSelectionState {
text: string;
rect: DOMRect | null;
}
/** Tracks the current user text selection. */
export function useTextSelection(): TextSelectionState & {
clear: () => void;
} {
const [state, setState] = useState<TextSelectionState>({
text: '',
rect: null,
});
const update = useCallback(() => {
if (!isBrowser()) return;
const selection = window.getSelection();
const text = selection?.toString() ?? '';
let rect: DOMRect | null = null;
if (selection && selection.rangeCount > 0 && text) {
rect = selection.getRangeAt(0).getBoundingClientRect();
}
setState({ text, rect });
}, []);
const clear = useCallback(() => {
if (isBrowser()) {
window.getSelection()?.removeAllRanges();
}
setState({ text: '', rect: null });
}, []);
useEffect(() => {
if (!isBrowser()) return;
document.addEventListener('selectionchange', update);
return () => document.removeEventListener('selectionchange', update);
}, [update]);
return { ...state, clear };
}
Copy-paste example
useTextSelection.example.tsx
'use client';
import { useTextSelection } from '@/hooks';
export function SelectionToolbar() {
const { text, clear } = useTextSelection();
if (!text) return null;
return (
<div>
Selected: {text}
<button onClick={clear}>Clear</button>
</div>
);
}Production checklist
- Called only from Client Components or other custom hooks
- Type parameters filled in (e.g.
useFetch<User[]>) - Tip: Lifecycle hooks are for side effects only — not for deriving render state.
- Source of truth: open
hooks/utility/useTextSelection.tsfor implementation details