### Install, Lint, and Test Dependencies Source: https://github.com/childrentime/reactuse/blob/main/CLAUDE.md Standard commands for managing project dependencies and running quality checks. Use these for local development setup and maintenance. ```bash pnpm install # install dependencies pnpm lint # eslint pnpm test # vitest ``` -------------------------------- ### Basic useRafState Example for a Floating Card Source: https://github.com/childrentime/reactuse/blob/main/packages/website-astro/src/content/blog/2026-05-27-react-render-loop-hooks.md This example demonstrates how to use `useRafState` to update the position of a floating card based on mouse movement. It shows the typical setup for visual state synchronization. ```tsx import { useRafState } from '@reactuses/core'; import { useEventListener } from '@reactuses/core'; function FloatingCard() { const [pos, setPos] = useRafState({ x: 0, y: 0 }); useEventListener('mousemove', (e) => { setPos({ x: e.clientX, y: e.clientY }); }); return (
card
); } ``` -------------------------------- ### Install @reactuses/core with pnpm Source: https://github.com/childrentime/reactuse/blob/main/packages/website-astro/src/content/blog/2026-03-11-react-window-size-hook.md Install the @reactuses/core package using pnpm. ```bash pnpm add @reactuses/core ``` -------------------------------- ### Install @reactuses/core with npm Source: https://github.com/childrentime/reactuse/blob/main/packages/website-astro/src/content/blog/2026-03-11-react-window-size-hook.md Install the @reactuses/core package using npm. ```bash npm i @reactuses/core ``` -------------------------------- ### Install @reactuses/core with yarn Source: https://github.com/childrentime/reactuse/blob/main/packages/website-astro/src/content/blog/2026-03-11-react-window-size-hook.md Install the @reactuses/core package using yarn. ```bash yarn add @reactuses/core ``` -------------------------------- ### Basic useTimeout Example Source: https://github.com/childrentime/reactuse/blob/main/packages/website-astro/src/content/docs/effect/useTimeout.mdx Demonstrates the basic usage of the `useTimeout` hook. The timer starts automatically on mount and can be restarted or canceled using buttons. The `isPending` state is displayed, showing whether the timer is active. ```tsx function Demo() { const [isPending, start, cancel] = useTimeout(5000); return (
Pending: {JSON.stringify(isPending)}
); }; ``` -------------------------------- ### useTimeoutFn Example Source: https://github.com/childrentime/reactuse/blob/main/packages/website-astro/public/llms-full.txt Demonstrates delaying a side effect with `useTimeoutFn`. The timer starts on mount and can be restarted. Requires manual calling of `start()` if `immediate: false` is passed. ```tsx function Demo() { const [text, setText] = useState("Please wait for 3 seconds"); const [isPending, start] = useTimeoutFn( () => { setText("Fired!"); }, 3000, { immediate: false }, ); return (

{text}

); }; ``` -------------------------------- ### Using useMediaDevices Hook for Camera Selection Source: https://github.com/childrentime/reactuse/blob/main/packages/website-astro/src/content/blog/2026-04-13-react-voice-speech-input.md This example shows how to use the `useMediaDevices` hook to automatically request permissions, get a list of video input devices, and provide a dropdown for selecting a camera. It also includes a button to manually refresh the device list. ```tsx import { useMediaDevices } from "@reactuses/core"; function CameraPicker({ selected, onSelect, }: { selected: string; onSelect: (id: string) => void; }) { const [{ devices }, ensurePermissions] = useMediaDevices({ requestPermissions: true, constraints: { video: true, audio: false }, }); const cameras = devices.filter((d) => d.kind === "videoinput"); return (
); } ``` -------------------------------- ### Install qrcode library Source: https://github.com/childrentime/reactuse/blob/main/packages/website-astro/src/content/docs/integrations/useQRCode.mdx Requires the 'qrcode' library to be installed separately. The hook will not function without it. ```shell npm i qrcode@^1 ``` -------------------------------- ### Install ReactUse Core Package Source: https://github.com/childrentime/reactuse/blob/main/packages/website-astro/src/content/blog/2026-03-11-ssr-safe-react-hooks.md Install the ReactUse core package using npm, pnpm, or yarn. ```bash npm i @reactuses/core ``` ```bash pnpm add @reactuses/core ``` ```bash yarn add @reactuses/core ``` -------------------------------- ### Basic useDropZone Example Source: https://github.com/childrentime/reactuse/blob/main/packages/website-astro/src/content/docs/element/useDropZone.mdx This example demonstrates how to use the useDropZone hook to create a drop zone. The `isOver` boolean is used to visually indicate when a file is being dragged over the zone. The callback function is currently empty but would typically handle the dropped files. ```tsx function Demo() { const ref = useRef(null); const isOver = useDropZone(ref, (_files) => {}); return (

Drop files into dropZone

{/* */}
isOverDropZone: {JSON.stringify(isOver)}
); }; ``` -------------------------------- ### Tracking Mouse Position with useRafState Source: https://github.com/childrentime/reactuse/blob/main/packages/website-astro/src/content/docs/state/useRafState.mdx This example demonstrates how to use useRafState to track mouse and touch coordinates, deferring updates to the next animation frame. It includes event listener setup and cleanup. ```tsx function Demo() { const [state, setState] = useRafState({ x: 0, y: 0 }); useMount(() => { const onMouseMove = (event: MouseEvent) => { setState({ x: event.clientX, y: event.clientY }); }; const onTouchMove = (event: TouchEvent) => { setState({ x: event.changedTouches[0].clientX, y: event.changedTouches[0].clientY, }); }; document.addEventListener("mousemove", onMouseMove); document.addEventListener("touchmove", onTouchMove); return () => { document.removeEventListener("mousemove", onMouseMove); document.removeEventListener("touchmove", onTouchMove); }; }); return
{JSON.stringify(state, null, 2)}
; }; ``` -------------------------------- ### Complete Landing Page Example with Scroll Hooks Source: https://github.com/childrentime/reactuse/blob/main/packages/website-astro/src/content/blog/2026-03-31-react-scroll-effects.md This example integrates multiple scroll-related hooks to manage a landing page's dynamic elements, including a progress bar, sticky header, smooth scrolling to sections, and modal scroll locking. Ensure all necessary hooks are imported from '@reactuses/core'. ```tsx import { useScroll, useScrollLock, useScrollIntoView, } from "@reactuses/core"; import { useSticky, useElementVisibility } from "@reactuses/core"; import { useRef, useState } from "react"; function LandingPage() { const scrollContainerRef = useRef(null); const pricingRef = useRef(null); const headerRef = useRef(null); // Track scroll for progress bar const [position] = useScroll(scrollContainerRef); // Sticky header detection const [isStuck] = useSticky(headerRef); // Smooth scroll to pricing const { scrollIntoView } = useScrollIntoView(pricingRef, { offset: 64, }); // Modal with scroll lock const [modalOpen, setModalOpen] = useState(false); useScrollLock( typeof document !== "undefined" ? document.body : null, modalOpen ); // Reveal pricing section const [pricingVisible] = useElementVisibility(pricingRef); const el = scrollContainerRef.current; const progress = el ? position.y / (el.scrollHeight - el.clientHeight) : 0; return (
{/* Progress bar */}
{/* Sticky header */}
MyApp
{/* Hero */}

Build amazing products

{/* Pricing with reveal */}

Pricing

Plans and details here.

{/* Modal */} {modalOpen && (

Contact Us

Page scroll is locked while this modal is open.

)}
); } ``` -------------------------------- ### Install ReactUse Core Package Source: https://github.com/childrentime/reactuse/blob/main/packages/website-astro/src/content/blog/2026-03-25-react-accessibility-hooks.md Install the ReactUse core package using npm. This is the first step to using any of the ReactUse hooks in your project. ```bash npm install @reactuses/core ``` -------------------------------- ### Install ts-document Source: https://github.com/childrentime/reactuse/blob/main/packages/ts-document/README.md Install the ts-document package as a development dependency. ```bash npm i ts-document -D ``` -------------------------------- ### SSE Server Implementation with Express Source: https://github.com/childrentime/reactuse/blob/main/packages/website-astro/src/content/docs/browser/useFetchEventSource.mdx This example demonstrates a basic SSE server using Express.js that handles POST requests to establish event streams, supports custom channels and intervals, and sends periodic messages. It includes CORS configuration and proper header setup for SSE. ```javascript const express = require('express'); const cors = require('cors'); const bodyParser = require('body-parser'); const app = express(); const PORT = 3001; // Store all active SSE connections const clients = new Map(); let messageCount = 0; app.use(cors({ origin: 'http://localhost:3000', methods: ['GET', 'POST', 'OPTIONS'], allowedHeaders: ['Content-Type', 'Cache-Control', 'Connection', 'Accept', 'Authorization'], exposedHeaders: ['Content-Type'], credentials: true, maxAge: 86400 })); app.options('*', cors()); // POST /events using raw request handling app.post('/events', async (req, res) => { // 1. Immediately set necessary headers res.setHeader('Content-Type', 'text/event-stream'); res.setHeader('Cache-Control', 'no-cache'); res.setHeader('Connection', 'keep-alive'); res.setHeader('X-Accel-Buffering', 'no'); res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000'); res.setHeader('Access-Control-Allow-Credentials', 'true'); // 2. Read and parse request body let body = ''; for await (const chunk of req) { body += chunk; } // 3. Parse configuration let config; try { config = body ? JSON.parse(body) : {}; } catch (e) { config = {}; } const channel = config.channel || 'default'; const interval = parseInt(config.interval) || 3000; // 4. Disable request timeout req.socket.setTimeout(0); req.socket.setNoDelay(true); req.socket.setKeepAlive(true); // 5. Start sending data console.log(`New client connected to channel: ${channel}`); // 6. Add connection to the client collection of corresponding channel if (!clients.has(channel)) { clients.set(channel, new Set()); } clients.get(channel).add(res); const totalClients = Array.from(clients.values()) .reduce((sum, set) => sum + set.size, 0); console.log(`Client connected to channel ${channel}. Total clients: ${totalClients}`); // 7. Send connection success message const sendEvent = (data, eventType = null) => { if (eventType) { res.write(`event: ${eventType}\n`); } res.write(`id: ${Date.now()}\n`); res.write(`data: ${JSON.stringify(data)}\n\n`); }; // 8. Send initial message try { sendEvent({ message: 'Connected to SSE stream', channel: channel, time: new Date().toISOString() }, 'connected'); // 9. Set up periodic message sending let messageCounter = 0; const intervalId = setInterval(() => { messageCounter++; messageCount++; try { sendEvent({ id: messageCount, count: messageCounter, channel: channel, time: new Date().toISOString(), message: `Channel ${channel} message ${messageCounter}` }); } catch (error) { console.error(`Error sending message to channel ${channel}:`, error); cleanup(); } }, interval); const cleanup = () => { clearInterval(intervalId); clients.get(channel).delete(res); console.log(`Client disconnected from channel ${channel}.`); if (clients.get(channel).size === 0) { clients.delete(channel); } res.end(); }; // 10. Handle client disconnection req.on('close', () => { cleanup(); }); req.on('error', (err) => { console.error(`Request error on channel ${channel}:`, err); cleanup(); }); } catch (error) { console.error(`Error setting up SSE for channel ${channel}:`, error); res.status(500).send('Internal Server Error'); } }); app.listen(PORT, () => { console.log(`SSE server listening on port ${PORT}`); }); ``` -------------------------------- ### Install @reactuses/core Package Source: https://github.com/childrentime/reactuse/blob/main/packages/website-astro/src/content/blog/2026-03-10-detect-click-outside-react.md Command to install the ReactUse core package, which provides the `useClickOutside` hook and other utility hooks. ```bash npm i @reactuses/core ``` -------------------------------- ### Basic Dialog Example Source: https://github.com/childrentime/reactuse/blob/main/packages/website-astro/public/llms-full.txt A simple React component demonstrating a dialog trigger button. This example is not directly related to useSpeechRecognition but shows a common UI pattern. ```jsx return (
Open Dialog } />

Open the dialog and try scrolling. You'll be able to scroll within the dialog content while background scrolling remains locked.

); ``` -------------------------------- ### Basic useScriptTag Example with jQuery Source: https://github.com/childrentime/reactuse/blob/main/packages/website-astro/public/llms-full.txt Demonstrates how to use useScriptTag to load jQuery and display its version. The script is automatically managed by the hook. ```tsx import { useScriptTag } from '@reactuses/core'; import { useEffect, useState } from 'react'; // Add this if you are using TypeScript // declare const jQuery: any; function Demo() { const [, status] = useScriptTag( "https://code.jquery.com/jquery-3.5.1.min.js", ); const [version, setVersion] = useState(0); useEffect(() => { if (typeof jQuery !== "undefined") { setVersion(jQuery.fn.jquery); } }, [status]); return
jQuery version: {version}
; }; ``` -------------------------------- ### GET SSE Endpoint Handler Source: https://github.com/childrentime/reactuse/blob/main/packages/website-astro/public/llms-full.txt Defines the Express.js route for handling incoming GET requests to the SSE endpoint. It extracts the channel and interval from query parameters and calls the main connection handler. ```javascript // GET SSE endpoint app.get('/events', (req, res) => { const channel = req.query.channel || 'default'; const interval = parseInt(req.query.interval) || 3000; handleGETConnection(req, res, channel, interval); }); ``` -------------------------------- ### Combine useHover and internal refs with useMergedRefs Source: https://github.com/childrentime/reactuse/blob/main/packages/website-astro/public/llms-full.txt This example demonstrates combining a ref for useHover with a button's ref using useMergedRefs. It also includes functionality to focus the button by pressing the 'F' key. ```tsx import { useRef, useEffect } from 'react'; import { render, useHover, useToggle, useMergedRefs } from '@reactuses/core'; function Demo() { const hoverRef = useRef(null); const buttonRef = useRef(null); const isHovered = useHover(hoverRef); const [isFocused, toggleFocus] = useToggle(false); const mergedRef = useMergedRefs(hoverRef, buttonRef); useEffect(() => { const handleKeyPress = (event) => { if (event.key === 'f' || event.key === 'F') { buttonRef.current?.focus(); } }; window.addEventListener('keypress', handleKeyPress); return () => { window.removeEventListener('keypress', handleKeyPress); }; }, []); const handleFocus = () => toggleFocus(true); const handleBlur = () => toggleFocus(false); return (

Press 'F' key to focus the button

); }; render(); ``` -------------------------------- ### useRafFn: Basic Animation Loop Source: https://github.com/childrentime/reactuse/blob/main/packages/website-astro/public/llms-full.txt Demonstrates how to use useRafFn to create a simple animation loop that updates a counter and displays the last high-resolution timestamp. The loop can be started and stopped imperatively. ```tsx function Demo() { const [ticks, setTicks] = useState(0); const [lastCall, setLastCall] = useState(0); const update = useUpdate(); const [loopStop, loopStart, isActive] = useRafFn((time) => { setTicks(ticks => ticks + 1); setLastCall(time); }); return (
RAF triggered: {ticks} (times)
Last high res timestamp: {lastCall}

); }; ``` -------------------------------- ### Multi-language Speech Recognition Demo Source: https://github.com/childrentime/reactuse/blob/main/packages/website-astro/public/llms-full.txt This component allows users to select a language and then start speech recognition. It displays the recognized text and provides start/stop controls. Ensure the browser supports the Web Speech API. ```tsx function Demo() { const [selectedLang, setSelectedLang] = React.useState('en-US'); const { isSupported, isListening, result, start, stop, } = useSpeechRecognition({ lang: selectedLang, continuous: true, interimResults: true, }); const languages = [ { code: 'en-US', name: 'English (US)' }, { code: 'zh-CN', name: '中文 (简体)' }, { code: 'ja-JP', name: '日本語' }, { code: 'ko-KR', name: '한국어' }, { code: 'es-ES', name: 'Español' }, { code: 'fr-FR', name: 'Français' }, ]; if (!isSupported) { return
Speech recognition is not supported
; } return (
{result || `Start speaking in ${languages.find(l => l.code === selectedLang)?.name}...`}
); } ``` -------------------------------- ### Track Device Orientation with useOrientation Source: https://github.com/childrentime/reactuse/blob/main/packages/website-astro/public/llms-full.txt This snippet demonstrates how to use the useOrientation hook to get the current device orientation state and display it. It returns the orientation's angle and type. ```tsx function Demo() { const [state] = useOrientation(); return
{JSON.stringify(state, null, 2)}
; }; ``` -------------------------------- ### GET /events Source: https://github.com/childrentime/reactuse/blob/main/packages/website-astro/public/llms-full.txt Establishes a Server-Sent Events connection for a specific channel. Clients can subscribe to real-time updates on a designated channel. The connection will periodically send heartbeat messages and broadcast updates at a specified interval. ```APIDOC ## GET /events ### Description Establishes a Server-Sent Events (SSE) connection to receive real-time updates. Clients can specify a channel and an interval for receiving messages. The server sends periodic messages and heartbeats to maintain the connection. ### Method GET ### Endpoint /events ### Query Parameters - **channel** (string) - Optional - The channel to subscribe to. Defaults to 'default'. - **interval** (integer) - Optional - The interval in milliseconds between messages. Defaults to 3000. ### Response #### Success Response (200) - **Content-Type**: text/event-stream - **Cache-Control**: no-cache - **Connection**: keep-alive - **X-Accel-Buffering**: no - **Access-Control-Allow-Origin**: http://localhost:3000 - **Access-Control-Allow-Credentials**: true ### Response Example (Connection established, subsequent messages are SSE formatted) ``` event: connected id: 1678886400000 data: {"message":"Connected to SSE stream","channel":"default","time":"2023-03-15T10:00:00.000Z"} event: broadcast id: 1678886403000 data: {"id":1,"count":1,"channel":"default","time":"2023-03-15T10:00:03.000Z","message":"Channel default message 1"} : ``` ``` -------------------------------- ### Get Device Pixel Ratio Source: https://github.com/childrentime/reactuse/blob/main/packages/website-astro/public/llms-full.txt Use this hook to display the current device pixel ratio. It is SSR-safe, returning a default of 1 on the server. ```tsx function Demo() { const { pixelRatio } = useDevicePixelRatio(); return

Device pixel ratio: {pixelRatio}

; }; ``` -------------------------------- ### Check Component Mount Status with useMountedState Source: https://github.com/childrentime/reactuse/blob/main/packages/website-astro/public/llms-full.txt Use this hook to get a stable function that returns true if the component is mounted. Call the returned function (e.g., isMounted()) to check the status, which is useful for guarding state updates in async operations. ```tsx function Demo() { const isMounted = useMountedState(); const [, update] = useState(0); useEffect(() => { update(1); }, []); return
This component is {isMounted() ? "MOUNTED" : "NOT MOUNTED"}
; }; ``` -------------------------------- ### Manually Listing Media Devices with Permissions Source: https://github.com/childrentime/reactuse/blob/main/packages/website-astro/src/content/blog/2026-04-13-react-voice-speech-input.md This example demonstrates the manual approach to listing media devices by first requesting permissions using `getUserMedia` to populate device labels, then enumerating devices. It includes setting up and cleaning up event listeners for device changes. ```tsx function ManualDeviceList() { const [devices, setDevices] = useState([]); useEffect(() => { let mounted = true; const refresh = async () => { try { // Trigger permission so labels are populated const stream = await navigator.mediaDevices.getUserMedia({ audio: true, video: true, }); stream.getTracks().forEach((t) => t.stop()); const list = await navigator.mediaDevices.enumerateDevices(); if (mounted) setDevices(list); } catch (e) { console.error(e); } }; refresh(); navigator.mediaDevices.addEventListener("devicechange", refresh); return () => { mounted = false; navigator.mediaDevices.removeEventListener("devicechange", refresh); }; }, []); return (
    {devices.map((d) => (
  • {d.kind}: {d.label || "(label hidden)"}
  • ))}
); } ``` -------------------------------- ### Force Component Re-render with useUpdate Source: https://github.com/childrentime/reactuse/blob/main/packages/website-astro/public/llms-full.txt Use this hook to get a stable function that forces a component re-render when called. It's helpful for updating values like Date.now() or integrating with external mutable states. The returned function's identity is stable across renders. ```tsx function Demo() { const update = useUpdate(); return ( <> {/* to avoid ssr error beacause date.now() will not be same in server and client */}
Time: {Date.now()}
); }; ``` -------------------------------- ### Select Current Pathname with useLocationSelector Source: https://github.com/childrentime/reactuse/blob/main/packages/website-astro/src/content/docs/browser/useLocationSelector.mdx This example demonstrates how to use `useLocationSelector` to get the current pathname. It also tracks the number of renders for the component. ```tsx function CurrentPathname() { const pathname = useLocationSelector(location => location.pathname); const ref = useRef(0); useEffect(() => { ref.current = ref.current + 1; }); return (
{pathname}
renderCount: {ref.current}
); } ``` -------------------------------- ### Basic useMount Example Source: https://github.com/childrentime/reactuse/blob/main/packages/website-astro/src/content/docs/effect/useMount.mdx Demonstrates how to use the `useMount` hook to update state once the component has mounted. This is useful for one-time initialization. ```tsx function Demo() { const [value, setValue] = useState("UnMounted"); useMount(() => { setValue("Mounted"); }); return
{value}
; }; ``` -------------------------------- ### Basic useDarkMode Hook Usage Source: https://github.com/childrentime/reactuse/blob/main/packages/website-astro/src/content/docs/browser/useDarkMode.mdx This example demonstrates the basic usage of the useDarkMode hook. It shows how to get the current theme state and the toggle function, and how to use them in a React component. ```tsx function Demo() { const [theme, toggleDark] = useDarkMode({ classNameDark: "dark", classNameLight: "light", defaultValue: false, }); return (
theme: {theme ? "dark" : "light"}

); } ``` -------------------------------- ### useRafFn Example Source: https://github.com/childrentime/reactuse/blob/main/packages/website-astro/src/content/docs/effect/useRafFn.mdx Demonstrates how to use useRafFn to trigger a callback on each animation frame. The callback receives a high-resolution timestamp. Controls are provided to start, stop, and check the active state of the loop. ```tsx function Demo() { const [ticks, setTicks] = useState(0); const [lastCall, setLastCall] = useState(0); const update = useUpdate(); const [loopStop, loopStart, isActive] = useRafFn((time) => { setTicks(ticks => ticks + 1); setLastCall(time); }); return (
RAF triggered: {ticks} (times)
Last high res timestamp: {lastCall}

); }; ``` -------------------------------- ### useTimeoutFn with Immediate Option Disabled Source: https://github.com/childrentime/reactuse/blob/main/packages/website-astro/src/content/blog/2026-05-18-react-timer-hooks.md This example shows how to use useTimeoutFn with the `immediate: false` option to defer the timer's execution. The timer will only start when explicitly scheduled, useful for scenarios like debouncing user input. ```tsx const [, , scheduleSave] = useTimeoutFn(saveDraft, 2000, { immediate: false }); return