### Install Reactuse Core Source: https://www.reactuse.com/index Installs the core package of Reactuse using npm. This package contains essential custom React Hooks. ```bash npm i @reactuses/core ``` -------------------------------- ### Install Reactuse Core Source: https://www.reactuse.com/zh-Hans This snippet shows how to install the core package of Reactuse using npm. Reactuse is a collection of custom React Hooks for enhancing functional components. ```bash npm i @reactuses/core ``` -------------------------------- ### Reactuse useToggle Hook Example Source: https://www.reactuse.com/index Demonstrates the usage of the `useToggle` hook from Reactuse. It shows how to manage a boolean state and provides buttons to toggle it. ```javascript import{ useToggle }from'@reactuses/core' functionDemo(){ const[on, toggle]=useToggle(true) return(
{on ?'ON':'OFF'}
Toggle toggle(true)}>set ON toggle(false)}>set OFF
) } ``` -------------------------------- ### useFirstMountState Usage Example Source: https://www.reactuse.com/state/useFirstMountState Demonstrates how to use the useFirstMountState hook in a React component. It shows how to get the initial mount state and display it, along with a button to trigger re-renders. ```jsx function Demo(){ const isFirstMount = useFirstMountState(); const [render, reRender] = useState(0); return(
This component is just mounted: {isFirstMount ? "YES" : "NO"}
); }; ``` -------------------------------- ### useFirstMountState Usage Example Source: https://www.reactuse.com/state/usefirstmountstate Demonstrates how to use the useFirstMountState hook in a React component. It shows how to get the initial mount state and display it, along with a button to trigger re-renders. ```jsx function Demo() { const isFirstMount = useFirstMountState(); const [render, reRender] = useState(0); return (
This component is just mounted: {isFirstMount ? "YES" : "NO"}
); }; ``` -------------------------------- ### useTimeout Usage Example Source: https://www.reactuse.com/effect/usetimeout Demonstrates how to use the useTimeout hook to manage a timer. It shows how to start the timer, cancel it, and display the pending state. ```javascript function Demo(){ const [isPending, start, cancel] = useTimeout(5000); return(
Pending: {JSON.stringify(isPending)}
); }; ``` -------------------------------- ### useTimeout Hook Example Source: https://www.reactuse.com/zh-Hans/effect/useTimeout Demonstrates how to use the useTimeout hook to manage a timer. It shows how to start the timer, cancel it, and display its pending state. ```javascript function Demo() { const [isPending, start, cancel] = useTimeout(5000); return (
Pending: {JSON.stringify(isPending)}
); }; ``` -------------------------------- ### React useTimeout Hook Example Source: https://www.reactuse.com/effect/useTimeout Demonstrates how to use the useTimeout hook to manage a timer. It shows how to start the timer, display its pending state, and cancel it. ```javascript function Demo() { const [isPending, start, cancel] = useTimeout(5000); return (
Pending: {JSON.stringify(isPending)}
); } ``` -------------------------------- ### Install useQRCode Source: https://www.reactuse.com/integrations/useQRCode Installs the qrcode library, a dependency for the useQRCode hook, using npm. ```bash npm i qrcode@^1 ``` -------------------------------- ### Install useQRCode with npm Source: https://www.reactuse.com/integrations/useqrcode This snippet shows how to install the qrcode library, a dependency for the useQRCode hook, using npm. ```bash npm i qrcode@^1 ``` -------------------------------- ### Use Toggle Hook in React Source: https://www.reactuse.com/zh-Hans Demonstrates the usage of the `useToggle` hook from Reactuse. This hook manages a boolean state and provides functions to toggle it. It's useful for managing on/off states in React components. ```javascript import{ useToggle }from'@reactuses/core' functionDemo(){ const[on, toggle]=useToggle(true) return(
{on ?'ON':'OFF'}
Toggle toggle(true)}>set ON toggle(false)}>set OFF
) } ``` -------------------------------- ### Install qrcode Package Source: https://www.reactuse.com/zh-Hans/integrations/useQRCode Installs the necessary 'qrcode' package version 1 or higher using npm for QR code generation. ```bash npm i qrcode@^1 ``` -------------------------------- ### React useWebNotification Example Source: https://www.reactuse.com/zh-Hans/browser/useWebNotification This example demonstrates how to use the `useWebNotification` hook to show and close desktop notifications. It checks for browser support and provides buttons to trigger the notification actions. ```javascript functionDemo(){ const{ isSupported, show, close }=useWebNotification(true); return(

Supported: {JSON.stringify(isSupported)}

{isSupported ?(
{ show("Hello, world from ReactUse!"); }}> Show Notification Close
):(
The Notification Web API is not supported in your browser.
)}
); } ``` -------------------------------- ### useRafFn Example Source: https://www.reactuse.com/effect/useRafFn Demonstrates how to use the useRafFn hook to trigger updates on each animation frame. It includes functionality to start, stop, and check the active state of the RAF loop. ```javascript functionDemo(){ 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}

); } ``` -------------------------------- ### usePlatform Hook Usage Source: https://www.reactuse.com/zh-Hans/browser/usePlatform This example demonstrates how to use the usePlatform hook to get the current platform information and display it in a React component. It imports the hook and destructures the platform from its return value. ```javascript function Demo(){ const {platform} = usePlatform(); return

platfrom: {platform}

; }; ``` -------------------------------- ### useMouse Hook Usage Example Source: https://www.reactuse.com/zh-Hans/browser/useMouse This example demonstrates how to use the `useMouse` hook to display the mouse's client, page, and screen coordinates. The hook returns an object containing various position properties. ```javascript function Demo() { const mouse = useMouse(); return (

Client - x: {mouse.clientX}, y: {mouse.clientY}

Page - x: {mouse.pageX}, y: {mouse.pageY}

Screen - x: {mouse.screenX}, y: {mouse.screenY}

); }; ``` -------------------------------- ### useObjectUrl Hook Usage Example Source: https://www.reactuse.com/browser/useObjectUrl This example demonstrates how to use the useObjectUrl hook to create and display a URL from a selected file. It includes an input for file selection and displays the generated object URL. ```typescript function Demo() { const [file, setFile] = useState(); const url = useObjectUrl(file); const onFileChange = (e: ChangeEvent) => { const target = e.target; const files = target.files; setFile(files && files.length > 0 ? files[0] : undefined); }; return (

Select File

Object Url

{url}
); } ``` -------------------------------- ### useCookie Hook Usage Example Source: https://www.reactuse.com/state/usecookie Demonstrates how to use the useCookie hook to manage cookie values. It includes functions to update, clear, and refresh the cookie, along with an example of how to change the cookie through other methods. ```JavaScript function Demo() { const defaultOption = { path: "/", }; const cookieName = "cookie-key"; const [cookieValue, updateCookie, refreshCookie] = useCookie( cookieName, defaultOption, "default-value" ); const updateButtonClick = () => { updateCookie("new-cookie-value"); }; const deleteButtonClick = () => { updateCookie(undefined); }; const change = () => { if ("cookieStore" in window) { const store = window.cookieStore; store.set({ name: cookieName, value: "changed" }); } else { document.cookie = `${cookieName}=changed; path=/`; } }; return (

Click on the button to update or clear the cookie

cookie: {cookieValue || "no value"}

); } ``` -------------------------------- ### useCookie Hook Usage Example Source: https://www.reactuse.com/state/useCookie Demonstrates how to use the useCookie hook to manage cookie values. It includes functions to update, clear, and refresh the cookie, along with an example of changing the cookie through other methods. ```javascript function Demo() { const defaultOption = { path: "/", }; const cookieName = "cookie-key"; const [cookieValue, updateCookie, refreshCookie] = useCookie( cookieName, defaultOption, "default-value" ); const updateButtonClick = () => { updateCookie("new-cookie-value"); }; const deleteButtonClick = () => { updateCookie(undefined); }; const change = () => { if ("cookieStore" in window) { const store = window.cookieStore; store.set({ name: cookieName, value: "changed" }); } else { document.cookie = `${cookieName}=changed; path=/`; } }; return (

Click on the button to update or clear the cookie

cookie: {cookieValue || "no value"}

); } ``` -------------------------------- ### useElementByPoint Usage Example Source: https://www.reactuse.com/browser/useelementbypoint This example demonstrates how to use the `useElementByPoint` hook in conjunction with `useMouse` and `useElementBounding` to highlight the element under the mouse cursor. It also includes functionality to pause and resume the element tracking. ```javascript functionDemo(){const{ clientX: x, clientY: y }=useMouse();const{ element, pause, resume }=useElementByPoint({ x, y });const bounding =useElementBounding(element);useEventListener("scroll", bounding.update,null,{ capture:true});const boxStyles =(()=>{if(element){return{ display:"block", width:`${bounding.width}px`, height:`${bounding.height}px`, left:`${bounding.left}px`, top:`${bounding.top}px`, backgroundColor:"#3eaf7c44", transition:"all 0.05s linear", position:"fixed", pointerEvents:"none", zIndex:9999, border:"1px solid var(--vp-c-brand)",};}return{ display:"none",};})();const pointStyles =(()=>({ transform:`translate(calc(${x}px - 50%), calc(${y}px - 50%))`, position:"fixed", top:0, left:0, pointerEvents:"none", width:"8px", height:"8px", borderRadius:"50%", backgroundColor:"#4ade80", boxShadow:"0 0 2px rgba(0,0,0,0.3)", zIndex:999,}))();return(<>X: {x}Y: {y}
PauseResume
);};render(); ``` -------------------------------- ### useCookie Hook Usage Example Source: https://www.reactuse.com/zh-Hans/state/useCookie Demonstrates how to use the useCookie hook to manage cookie values. It includes functions to update, clear, and refresh the cookie, along with an example of changing the cookie through other methods. ```javascript function Demo() { const defaultOption = { path: "/", }; const cookieName = "cookie-key"; const [cookieValue, updateCookie, refreshCookie] = useCookie( cookieName, defaultOption, "default-value" ); const updateButtonClick = () => { updateCookie("new-cookie-value"); }; const deleteButtonClick = () => { updateCookie(undefined); }; const change = () => { if ("cookieStore" in window) { const store = window.cookieStore; store.set({ name: cookieName, value: "changed" }); } else { document.cookie = `${cookieName}=changed; path=/`; } }; return (

Click on the button to update or clear the cookie

cookie: {cookieValue || "no value"}

); } ``` -------------------------------- ### useRafState Result Example Source: https://www.reactuse.com/state/useRafState Shows the expected JSON output for the state managed by the useRafState hook in the provided example, reflecting the tracked x and y coordinates. ```JSON { "x": 0, "y": 0 } ``` -------------------------------- ### React Use usePermission Hook Usage Example Source: https://www.reactuse.com/zh-Hans/browser/usePermission This example demonstrates how to use the `usePermission` hook to get the permission state for the microphone. It displays the state in a preformatted JSON string. ```jsx function Demo(){const state =usePermission({ name:"microphone"});return
{JSON.stringify(state,null,2)}
;}; ``` -------------------------------- ### Get Window Scroll Position with useWindowScroll Source: https://www.reactuse.com/zh-Hans/element/useWindowScroll This example demonstrates how to use the useWindowScroll hook to get the current scroll position of the browser window. The hook returns an object with 'x' and 'y' properties representing the horizontal and vertical scroll values, respectively. ```jsx function Demo() { return (
); } ``` -------------------------------- ### useTimeoutFn Example Source: https://www.reactuse.com/effect/useTimeoutFn Demonstrates how to use the useTimeoutFn hook to create a delayed action. The example shows a button that, when clicked, starts a 3-second timer. After the timer fires, it updates the text. The button also toggles between 'Restart' and 'Pending' states based on the timer's status. ```jsx function Demo() { const [text, setText] = useState("Please wait for 3 seconds"); const [isPending, start] = useTimeoutFn(() => { setText("Fired!"); }, 3000, { immediate: false, }); return (

{text}

); }; ``` -------------------------------- ### useSessionStorage Usage Example Source: https://www.reactuse.com/zh-Hans/state/useSessionStorage Demonstrates how to use the `useSessionStorage` hook to get and set values in sessionStorage. It includes buttons to update the value and remove it. ```javascript function Demo() { const [value, setValue] = useSessionStorage('my-key', 'key'); return (
Value: {value}
); } ``` -------------------------------- ### Usage Example of useQRCode Source: https://www.reactuse.com/integrations/useQRCode Demonstrates how to use the useQRCode hook to generate a QR code from user input. It includes state management for the input text and displays the generated QR code or any errors. ```typescript import { useQRCode } from "@reactuses/core/useQRCode"; function Demo() { const [text, setText] = useState("https://reactuse.com/"); const { qrCode, error } = useQRCode(text); return (
setText(e.target.value)} placeholder="Enter text to generate QR code" />

{error &&
{error}
} {qrCode && QR Code}
); } ``` -------------------------------- ### React Use useOrientation Hook Example Source: https://www.reactuse.com/zh-Hans/browser/useOrientation Demonstrates how to use the useOrientation hook to get the current device orientation state. It displays the angle and type of the orientation. ```jsx function Demo(){ const [state] = useOrientation(); return
{JSON.stringify(state, null, 2)}
; }; ``` -------------------------------- ### useMount Hook Usage Example Source: https://www.reactuse.com/effect/usemount Demonstrates how to use the useMount hook to update a component's state after it has been mounted. The hook takes a callback function that runs once on mount. ```javascript function Demo() { const [value, setValue] = useState("UnMounted"); useMount(() => { setValue("Mounted"); }); return
{value}
; } ``` -------------------------------- ### Node.js SSE Server Setup Source: https://www.reactuse.com/zh-Hans/browser/useFetchEventSource Sets up a Node.js server using Express to handle Server-Sent Events (SSE). It includes endpoints for SSE streams, broadcasting messages, and server status. The server manages client connections per channel and handles disconnections gracefully. ```javascript const express = require('express'); const bodyParser = require('body-parser'); const app = express(); const PORT = process.env.PORT || 3000; // In-memory store for clients, mapping channel names to sets of response objects const clients = new Map(); let messageCounter = 0; let messageCount = 0; // Helper function to handle GET requests for SSE connections const handleGETConnection = (req, res, channel, interval) => { // Set headers for SSE res.setHeader('Content-Type', 'text/event-stream'); res.setHeader('Cache-Control', 'no-cache'); res.setHeader('Connection', 'keep-alive'); res.flushHeaders(); // Flush headers immediately // Add the client response object to the correct channel if (!clients.has(channel)) { clients.set(channel, new Set()); } clients.get(channel).add(res); // Send initial data or start interval const intervalId = setInterval(() => { messageCounter++; messageCount++; sendEvent(res, { id: messageCount, count: messageCounter, channel: channel, time: new Date().toISOString(), message: `Channel ${channel} message ${messageCounter}` }); }, interval); // Heartbeat to keep the connection alive const heartbeatId = setInterval(() => { res.write(':\n\n'); // Send a comment line to keep connection alive }, 15000); // Cleanup function for when a client disconnects const cleanup = () => { clearInterval(intervalId); clearInterval(heartbeatId); const channelClients = clients.get(channel); if (channelClients) { channelClients.delete(res); if (channelClients.size === 0) { clients.delete(channel); } } const remainingClients = Array.from(clients.values()).reduce((sum, set) => sum + set.size, 0); console.log(`Client disconnected from channel ${channel}. Total clients: ${remainingClients}`); try { res.end(); } catch (error) { console.error('Error ending response:', error); } }; // Listen for connection close events req.on('close', cleanup); res.on('close', cleanup); res.on('error', cleanup); }; // Helper function to send data to a specific client const sendEvent = (res, data) => { res.write(`event: message\n`); res.write(`id: ${data.id}\n`); res.write(`data: ${JSON.stringify(data)}\n\n`); }; // 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); }); // Broadcast message endpoint app.post('/broadcast', bodyParser.json(), (req, res) => { const { message, channel, eventType = 'broadcast' } = req.body; let targetClients = new Set(); if (channel) { targetClients = clients.get(channel) || new Set(); console.log(`Broadcasting message to channel ${channel} (${targetClients.size} clients):`, message); } else { // Broadcast to all clients across all channels targetClients = new Set( Array.from(clients.values()).flatMap(channelClients => Array.from(channelClients)) ); console.log(`Broadcasting message to all channels (${targetClients.size} clients):`, message); } let successCount = 0; for (const client of targetClients) { try { client.write(`event: ${eventType}\n`); client.write(`id: ${Date.now()}\n`); client.write(`data: ${JSON.stringify({ message, channel: channel || 'all', time: new Date().toISOString() })} `); successCount++; } catch (error) { console.error('Error broadcasting to client:', error); } } res.json({ success: true, clientCount: targetClients.size, successfulBroadcasts: successCount, channel: channel || 'all', message: 'Broadcast sent successfully' }); }); // Status endpoint app.get('/status', (req, res) => { const channelStats = {}; clients.forEach((clientSet, channel) => { channelStats[channel] = clientSet.size; }); res.json({ activeConnections: Array.from(clients.values()).reduce((sum, set) => sum + set.size, 0), channelStats, messageCount, uptime: process.uptime() }); }); // Error handling middleware app.use((err, req, res, next) => { console.error('Server error:', err); res.status(500).json({ error: 'Internal Server Error', message: err.message }); }); // Start the server app.listen(PORT, () => { console.log(`SSE Server running at http://localhost:${PORT}`); console.log('Available endpoints:'); console.log(`- GET /events?channel={channel}&interval={interval} - SSE stream`); console.log(`- POST /broadcast - Broadcast message to all clients or specific channel`); console.log(`- GET /status - Server status`); }); ``` -------------------------------- ### Use useInterval Hook Source: https://www.reactuse.com/zh-Hans/effect/useInterval This example demonstrates how to use the useInterval hook to increment a counter every second. It shows the basic setup and how the hook integrates into a React component. ```javascript function Demo(){ const [count, setCount] = useState(0); useInterval(() => { setCount(count + 1); }, 1000); return
count: {count}
; }; ``` -------------------------------- ### useSessionStorage Hook Usage Example Source: https://www.reactuse.com/state/usesessionstorage Demonstrates how to use the useSessionStorage hook to manage a sessionStorage key. It shows how to get the current value, update it with new values, and remove it from storage. ```jsx function Demo() { // bind string const [value, setValue] = useSessionStorage("my-key", "key"); return (
Value: {value}
{/* delete data from storage */}
); }; ``` -------------------------------- ### Track Screen Orientation with useOrientation Source: https://www.reactuse.com/browser/useorientation This example demonstrates how to use the useOrientation hook to get the current screen orientation state. It displays the orientation type and angle in a JSON format. ```jsx function Demo(){ const [state] = useOrientation(); return
{JSON.stringify(state, null, 2)}
; }; ``` -------------------------------- ### React useClipboard Hook Example Source: https://www.reactuse.com/browser/useClipboard Demonstrates how to use the useClipboard hook to copy text to the user's clipboard. It includes input for text, a button to trigger the copy action, and displays the current clipboard content and clipboard permissions. ```javascript functionDemo(){ const[value, setValue]=useState(""); const[text, copy]=useClipboard(); const permissionRead =usePermission("clipboard-read"); const permissionWrite =usePermission("clipboard-write"); return(

Clipboard Permission: read {permissionRead} | write  {permissionWrite}

Current copied: {text ||"none"}

{ setValue(event.currentTarget.value); }} /> copy(value)}>Copy
); }; ``` -------------------------------- ### React useClipboard Hook Example Source: https://www.reactuse.com/browser/useclipboard Demonstrates how to use the useClipboard hook to copy text to the user's clipboard. It includes input for text, a button to trigger the copy action, and displays the current clipboard content and clipboard permissions. ```javascript functionDemo(){ const[value, setValue]=useState(""); const[text, copy]=useClipboard(); const permissionRead =usePermission("clipboard-read"); const permissionWrite =usePermission("clipboard-write"); return(

Clipboard Permission: read {permissionRead} | write  {permissionWrite}

Current copied: {text ||"none"}

{ setValue(event.currentTarget.value); }} /> copy(value)}>Copy
); }; ``` -------------------------------- ### useElementByPoint Hook Usage Example Source: https://www.reactuse.com/zh-Hans/browser/useElementByPoint This example demonstrates how to use the useElementByPoint hook in a React component. It utilizes useMouse to track cursor position and useElementBounding to get the dimensions of the detected element. The component displays the coordinates of the mouse pointer and highlights the element found at those coordinates with a bounding box. It also includes buttons to pause and resume the element detection. ```jsx function Demo(){const{ clientX: x, clientY: y }=useMouse();const{ element, pause, resume }=useElementByPoint({ x, y });const bounding =useElementBounding(element);useEventListener("scroll", bounding.update,null,{ capture:true});const boxStyles =(()=>{if(element){return{ display:"block", width:`${bounding.width}px`, height:`${bounding.height}px`, left:`${bounding.left}px`, top:`${bounding.top}px`, backgroundColor:"#3eaf7c44", transition:"all 0.05s linear", position:"fixed", pointerEvents:"none", zIndex:9999, border:"1px solid var(--vp-c-brand)",};}return{ display:"none",};})();const pointStyles =(()=>({ transform:`translate(calc(${x}px - 50%), calc(${y}px - 50%))`, position:"fixed", top:0, left:0, pointerEvents:"none", width:"8px", height:"8px", borderRadius:"50%", backgroundColor:"#4ade80", boxShadow:"0 0 2px rgba(0,0,0,0.3)", zIndex:999,}))();return(<>X: {x}Y: {y}
PauseResume
);}render(); ``` -------------------------------- ### useLocalStorage Hook Usage Example Source: https://www.reactuse.com/zh-Hans/state/useLocalStorage Demonstrates how to use the useLocalStorage hook to manage a string value in localStorage. It shows how to get the current value, update it with new strings, and remove it from storage. ```javascript function Demo() { // bind string const [value, setValue] = useLocalStorage("my-key", "key"); return (
Value: {value}
{/* delete data from storage */}
); } ``` -------------------------------- ### useDropZone Hook Usage Example Source: https://www.reactuse.com/zh-Hans/element/useDropZone Demonstrates how to use the `useDropZone` hook to create a drag-and-drop area for files. It shows how to attach the hook to a target element and display whether files are currently being dragged over the zone. ```javascript functionDemo(){ const ref =useRef(null); const isOver =useDropZone(ref,(_files)=>{}); return(

Drop files into dropZone

isOverDropZone: {JSON.stringify(isOver)}
); } ``` -------------------------------- ### useSessionStorage Hook Usage Example Source: https://www.reactuse.com/state/useSessionStorage Demonstrates how to use the useSessionStorage hook to manage a sessionStorage key. It shows how to get and set values, including setting the value to null to remove it from storage. ```jsx function Demo() { // bind string const [value, setValue] = useSessionStorage("my-key", "key"); return (
Value: {value}
{/* delete data from storage */}
); } ``` -------------------------------- ### useEventSource Hook Example Source: https://www.reactuse.com/browser/useEventSource This example demonstrates how to use the `useEventSource` hook to connect to an EventSource, display its status, data, and errors, and control the connection with open and close buttons. It initializes the hook with a specific URL and options, including `immediate: false` to manually control the connection. ```javascript functionDemo(){const{ status, data, error, close, open }=useEventSource("https://sse.dev/test",[],{ immediate:false,});return(
Status: {status}
Data: {JSON.stringify(data)}
Error: {error}
openClose
);}; ``` -------------------------------- ### useEventSource Hook Example Source: https://www.reactuse.com/browser/useeventsource This example demonstrates how to use the `useEventSource` hook to connect to an EventSource, display its status, data, and errors, and control the connection with open and close buttons. It initializes the hook with a specific URL and options, including `immediate: false` to manually control the connection. ```javascript functionDemo(){const{ status, data, error, close, open }=useEventSource("https://sse.dev/test",[],{ immediate:false,});return(
Status: {status}
Data: {JSON.stringify(data)}
Error: {error}
openClose
);}; ``` -------------------------------- ### useRafFn Example Source: https://www.reactuse.com/zh-Hans/effect/useRafFn Demonstrates how to use the useRafFn hook to trigger updates on each animation frame. It includes state management for ticks and the last timestamp, along with buttons to start and stop the animation. ```javascript functionDemo(){ 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}

); } ``` -------------------------------- ### useMount Hook Usage Example Source: https://www.reactuse.com/effect/useMount Demonstrates how to use the useMount hook to update component state after mounting. The hook takes a function that will be executed once the component is mounted. ```javascript function Demo() { const [value, setValue] = useState("UnMounted"); useMount(() => { setValue("Mounted"); }); return
{value}
; }; ``` -------------------------------- ### usePlatform Hook Usage Source: https://www.reactuse.com/browser/useplatform This example demonstrates how to use the usePlatform hook in a React component to display the detected platform. It imports the hook and uses it to get the platform value, which is then rendered in a paragraph tag. ```jsx function Demo() { const { platform } = usePlatform(); return

platfrom: {platform}

; } ``` -------------------------------- ### Multi Channel Example with useFetchEventSource Source: https://www.reactuse.com/browser/useFetchEventSource Shows an example of using the useFetchEventSource hook to switch between different event channels. It utilizes React's useState hook to manage the current channel and includes functions to close the existing connection, update the channel, and reopen the connection. The UI allows users to select a channel from a dropdown. ```javascript functionDemo(){ const[channel, setChannel]=useState('default'); const{ data, close, open }=useFetchEventSource("http://localhost:3001/events",{ method:"POST", immediate:false, body:JSON.stringify({ channel }), onMessage:(event)=>{ console.log(`Message from ${channel}:`, event); } }); const switchChannel=(newChannel)=>{ close(); setChannel(newChannel); open(); }; return(
Current Channel: {channel}
Latest Message: {data?.message}
); }; ``` -------------------------------- ### useScriptTag Usage Example Source: https://www.reactuse.com/zh-Hans/browser/useScriptTag Demonstrates how to use the useScriptTag hook to load an external JavaScript file (jQuery) and access its functionality. It shows how to get the script loading status and retrieve the jQuery version once loaded. ```javascript declareconst jQuery:any; functionDemo(){ 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}
; }; ``` -------------------------------- ### useLocalStorage Hook Usage Example Source: https://www.reactuse.com/state/useLocalStorage Demonstrates how to use the useLocalStorage hook to manage a string value in localStorage. It shows how to get, set, and remove data, and includes buttons for updating the value and deleting it from storage. ```jsx function Demo() { // bind string const [value, setValue] = useLocalStorage("my-key", "key"); return (
Value: {value}
{/* delete data from storage */}
); }; ``` -------------------------------- ### Multi Channel Example with useFetchEventSource Source: https://www.reactuse.com/browser/usefetcheventsource Shows an example of using the useFetchEventSource hook to switch between different event channels. It utilizes React's useState hook to manage the current channel and includes functions to close the existing connection, update the channel, and reopen the connection. The UI allows users to select a channel from a dropdown. ```javascript functionDemo(){ const[channel, setChannel]=useState('default'); const{ data, close, open }=useFetchEventSource("http://localhost:3001/events",{ method:"POST", immediate:false, body:JSON.stringify({ channel }), onMessage:(event)=>{ console.log(`Message from ${channel}:`, event); } }); const switchChannel=(newChannel)=>{ close(); setChannel(newChannel); open(); }; return(
Current Channel: {channel}
Latest Message: {data?.message}
); }; ``` -------------------------------- ### Query Microphone Permission Status Source: https://www.reactuse.com/browser/usePermission This example demonstrates how to use the usePermission hook to get the current permission state for the microphone. The hook returns the permission state, which is then displayed in a preformatted text element. ```jsx function Demo() { const state = usePermission({ name: "microphone" }); return
{JSON.stringify(state, null, 2)}
; }; ``` -------------------------------- ### useCounter Hook Example Source: https://www.reactuse.com/state/usecounter Demonstrates the usage of the useCounter hook to manage a numeric state with increment, decrement, set, and reset functions. It includes setting initial values and constraints for min and max. ```jsx function Demo() { const [current, set, inc, dec, reset] = useCounter(10, 100, 1); return (

{current} max: 100; min: 1;

); } ``` -------------------------------- ### React useCssVar Hook Example Source: https://www.reactuse.com/zh-Hans/browser/useCssVar Demonstrates how to use the `useCssVar` hook to get and set CSS variables on a DOM element. It includes a function to toggle a CSS variable's value and display the current value. ```jsx functionDemo(){const key ="--color";const ref =useRef(null);const[color, setColor]=useCssVar(key, ref,"" );const style:any={"--color":"#7fa998","color":"var(--color)",};constswitchColor=()=>{if(color ==="#df8543"){setColor("#7fa998");}else{setColor("#df8543");}};return(
Sample text, <>{color}Change Color
);} ``` -------------------------------- ### Get Window Scroll Position (React Hook) Source: https://www.reactuse.com/element/usewindowscroll This example demonstrates how to use the useWindowScroll hook to retrieve the horizontal and vertical scroll positions of the browser window. It's a React hook designed for this specific purpose. ```jsx function Demo() { return (
); } ``` -------------------------------- ### Query Microphone Permission Status with usePermission Source: https://www.reactuse.com/browser/usepermission This example demonstrates how to use the usePermission hook to get the current status of the microphone permission. It initializes the hook with 'microphone' as the permission name and displays the resulting state. ```jsx function Demo(){ const state = usePermission({ name: "microphone" }); return
{JSON.stringify(state, null, 2)}
; }; ```