typescriptintermediate
useSpeechSynthesis Hook
Text-to-speech hook using the Web Speech API with voice selection, rate, and pitch control.
typescriptPress ⌘/Ctrl + Shift + C to copy
import { useState, useEffect, useCallback } from 'react';
export function useSpeechSynthesis() {
const [voices, setVoices] = useState<SpeechSynthesisVoice[]>([]);
const [speaking, setSpeaking] = useState(false);
useEffect(() => {
const loadVoices = () => setVoices(speechSynthesis.getVoices());
loadVoices();
speechSynthesis.onvoiceschanged = loadVoices;
return () => { speechSynthesis.onvoiceschanged = null; };
}, []);
const speak = useCallback((text: string, options?: {
voice?: SpeechSynthesisVoice;
rate?: number;
pitch?: number;
}) => {
const utterance = new SpeechSynthesisUtterance(text);
if (options?.voice) utterance.voice = options.voice;
utterance.rate = options?.rate ?? 1;
utterance.pitch = options?.pitch ?? 1;
utterance.onstart = () => setSpeaking(true);
utterance.onend = () => setSpeaking(false);
speechSynthesis.speak(utterance);
}, []);
const stop = useCallback(() => {
speechSynthesis.cancel();
setSpeaking(false);
}, []);
return { voices, speaking, speak, stop };
}Use Cases
- Accessibility features
- Voice assistants
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
typescriptadvanced
useFocusTrap Hook
Traps keyboard focus within a container for accessible modals and dialogs.
Best for: Accessible modals
#hooks#a11y
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