### Implement responsive UI with useMediaQuery Source: https://usehooks.com/usemediaquery This example demonstrates how to use the hook to conditionally render UI elements based on different viewport width breakpoints. ```javascript import * as React from "react"; import { useMediaQuery } from "@uidotdev/usehooks"; import { phone, tablet, laptop, desktop } from "./icons"; export default function App() { const isSmallDevice = useMediaQuery("only screen and (max-width : 768px)"); const isMediumDevice = useMediaQuery( "only screen and (min-width : 769px) and (max-width : 992px)" ); const isLargeDevice = useMediaQuery( "only screen and (min-width : 993px) and (max-width : 1200px)" ); const isExtraLargeDevice = useMediaQuery( "only screen and (min-width : 1201px)" ); return (

useMediaQuery

Resize your browser windows to see changes.
{phone}
Small
{tablet}
Medium
{laptop}
Large
{desktop}
Extra Large
); } ``` ```javascript import * as React from "react"; import { useMediaQuery } from "@uidotdev/usehooks"; import { phone, tablet, laptop, desktop } from "./icons"; export default function App() { const isSmallDevice = useMediaQuery("only screen and (max-width : 768px)"); const isMediumDevice = useMediaQuery( "only screen and (min-width : 769px) and (max-width : 992px)" ); const isLargeDevice = useMediaQuery( "only screen and (min-width : 993px) and (max-width : 1200px)" ); const isExtraLargeDevice = useMediaQuery( "only screen and (min-width : 1201px)" ); return (

useMediaQuery

Resize your browser windows to see changes.
{phone}
Small
{tablet}
Medium
{laptop}
Large
{desktop}
Extra Large
); } ``` -------------------------------- ### Implement useCounter with min and max limits Source: https://usehooks.com/usecounter Demonstrates initializing the hook with a starting value and boundary options, and utilizing the returned control functions. ```javascript import * as React from "react"; import { useCounter } from "@uidotdev/usehooks"; export default function App() { const [count, { increment, decrement, set, reset }] = useCounter(5, { min: 5, max: 10, }); return (

UseCounter

with optional min / max

{count}

); } ``` ```javascript import * as React from "react"; import { useCounter } from "@uidotdev/usehooks"; export default function App() { const [count, { increment, decrement, set, reset }] = useCounter(5, { min: 5, max: 10, }); return (

UseCounter

with optional min / max

{count}

); } ``` -------------------------------- ### useCounter(startingValue, options) Source: https://usehooks.com/usecounter Initializes a counter with an optional starting value and constraints. ```APIDOC ## useCounter(startingValue, options) ### Description Manages a counter value with optional minimum and maximum limits. If the starting value is outside the specified limits, an error is thrown. ### Parameters - **startingValue** (number) - Optional - The initial value for the counter. Default is 0. - **options** (object) - Optional - Configuration object. - **min** (number) - Optional - The minimum value allowed. - **max** (number) - Optional - The maximum value allowed. ### Return Value Returns an array containing: - **[0]** (number) - The current value of the counter. - **[1]** (object) - An object containing control functions: - **increment()** - Increments the counter by 1. - **decrement()** - Decrements the counter by 1. - **set(nextCount: number)** - Sets the counter to the specified value. - **reset()** - Resets the counter to the initial startingValue. ### Usage Example ```javascript const [count, { increment, decrement, set, reset }] = useCounter(5, { min: 5, max: 10, }); ``` ``` -------------------------------- ### Implement useDebounce for Search Input Source: https://usehooks.com/usedebounce This example demonstrates using useDebounce to delay search requests while a user types in an input field. ```javascript import * as React from "react"; import { useDebounce } from "@uidotdev/usehooks"; import searchHackerNews from "./searchHackerNews"; import SearchResults from "./SearchResults"; export default function App() { const [searchTerm, setSearchTerm] = React.useState("js"); const [results, setResults] = React.useState([]); const [isSearching, setIsSearching] = React.useState(false); const debouncedSearchTerm = useDebounce(searchTerm, 300); const handleChange = (e) => { setSearchTerm(e.target.value); }; const handleSubmit = (e) => { e.preventDefault(); const formData = new FormData(e.target); setSearchTerm(formData.get("search")); e.target.reset(); e.target.focus(); }; React.useEffect(() => { const searchHN = async () => { let results = []; setIsSearching(true); if (debouncedSearchTerm) { const data = await searchHackerNews(debouncedSearchTerm); results = data?.hits || []; } setIsSearching(false); setResults(results); }; searchHN(); }, [debouncedSearchTerm]); return (

useDebounce

); } ``` ```javascript import * as React from "react"; import { useDebounce } from "@uidotdev/usehooks"; import searchHackerNews from "./searchHackerNews"; import SearchResults from "./SearchResults"; export default function App() { const [searchTerm, setSearchTerm] = React.useState("js"); const [results, setResults] = React.useState([]); const [isSearching, setIsSearching] = React.useState(false); const debouncedSearchTerm = useDebounce(searchTerm, 300); const handleChange = (e) => { setSearchTerm(e.target.value); }; const handleSubmit = (e) => { e.preventDefault(); const formData = new FormData(e.target); setSearchTerm(formData.get("search")); e.target.reset(); e.target.focus(); }; React.useEffect(() => { const searchHN = async () => { let results = []; setIsSearching(true); if (debouncedSearchTerm) { const data = await searchHackerNews(debouncedSearchTerm); results = data?.hits || []; } setIsSearching(false); setResults(results); }; searchHN(); }, [debouncedSearchTerm]); return (

useDebounce

); } ``` -------------------------------- ### Track window dimensions with useWindowSize Source: https://usehooks.com/usewindowsize This example demonstrates how to use the useWindowSize hook to display current window dimensions and adjust a component's style dynamically. ```javascript import * as React from "react"; import { useWindowSize } from "@uidotdev/usehooks"; function Browser({ size }) { return (
); } export default function App() { const size = useWindowSize(); return (

useWindowSize

Resize the window

width {size.width}
height {size.height}
); } ``` -------------------------------- ### Implement useKeyPress for arrow key detection Source: https://usehooks.com/usekeypress This example demonstrates how to use the hook to listen for arrow key presses and update the UI state accordingly. ```javascript import * as React from "react"; import { useKeyPress } from "@uidotdev/usehooks"; export default function App() { const [activeKey, setActiveKey] = React.useState(""); useKeyPress("ArrowRight", onKeyPress); useKeyPress("ArrowLeft", onKeyPress); useKeyPress("ArrowUp", onKeyPress); useKeyPress("ArrowDown", onKeyPress); function onKeyPress(e) { e.preventDefault(); setActiveKey(e.key); setTimeout(() => { setActiveKey(""); }, 600); } return (

useKeyPress

Press one of the arrow keys on your keyboard

{Boolean(activeKey) && }
); } ``` -------------------------------- ### Implement useSessionStorage in a React component Source: https://usehooks.com/usesessionstorage This example demonstrates how to initialize and update a state value that persists in session storage. ```javascript import * as React from "react"; import { useSessionStorage } from "@uidotdev/usehooks"; import { cart } from "./icons"; export default function App() { const [count, setCount] = useSessionStorage("woot", 0); return (

useSessionStorage

); } ``` ```javascript import * as React from "react"; import { useSessionStorage } from "@uidotdev/usehooks"; import { cart } from "./icons"; export default function App() { const [count, setCount] = useSessionStorage("woot", 0); return (

useSessionStorage

); } ``` -------------------------------- ### Implement a conditional interval timer with useIntervalWhen Source: https://usehooks.com/useintervalwhen This example demonstrates how to toggle an interval timer using a boolean state and the useIntervalWhen hook. ```javascript import * as React from "react"; import { useIntervalWhen } from "@uidotdev/usehooks"; export default function App() { const [count, setCount] = React.useState(0); const [when, setWhen] = React.useState(false); useIntervalWhen( () => { setCount((c) => c + 0.1); }, { ms: 100, when, startImmediately: true } ); return (

useIntervalWhen

); } ``` -------------------------------- ### Implement useIntersectionObserver for lazy loading Source: https://usehooks.com/useintersectionobserver This example demonstrates how to use the hook to conditionally render content only when the element enters the viewport. ```javascript import * as React from "react"; import { useIntersectionObserver } from "@uidotdev/usehooks"; import demoData from "./demoData"; const Section = ({ imgUrl, caption, href }) => { const [ref, entry] = useIntersectionObserver({ threshold: 0, root: null, rootMargin: "0px", }); return (
{entry?.isIntersecting && ( <> {caption}
{caption}
)}
); }; export default function App() { return (

useIntersectionObserver

(Memes from bytes.dev)
{demoData.map(({ imgUrl, href, caption }, index) => { return (
); })}
); } ``` -------------------------------- ### Display network state in a React component Source: https://usehooks.com/usenetworkstate This example demonstrates how to use the useNetworkState hook to retrieve and display current network connection properties in a table. ```javascript import * as React from "react"; import { useNetworkState } from "@uidotdev/usehooks"; export default function App() { const network = useNetworkState(); return (

useNetworkState

{Object.keys(network).map((key) => { return ( ); })}
{key} {`${network[key]}`}
); } ``` -------------------------------- ### Implementing useGeolocation in a React Component Source: https://usehooks.com/usegeolocation This example demonstrates how to integrate the useGeolocation hook to handle loading, error, and success states when accessing user location. ```javascript import * as React from "react"; import { useGeolocation } from "@uidotdev/usehooks"; import Demo from "./Demo"; export default function App() { return (

useGeolocation

); } function Location() { const state = useGeolocation(); if (state.loading) { return

loading... (you may need to enable permissions)

; } if (state.error) { return

Enable permissions to access your location data

; } return ; } ``` -------------------------------- ### Tracking mouse coordinates with useMouse Source: https://usehooks.com/usemouse This example demonstrates how to use the useMouse hook to track mouse position relative to an element and determine intersection status. ```javascript import * as React from "react"; import { useMouse } from "@uidotdev/usehooks"; import Demo from "./Demo"; export default function App() { const [mouse, ref] = useMouse(); const xIntersecting = mouse.elementX > 0 && mouse.elementX < 300; const yIntersecting = mouse.elementY > 0 && mouse.elementY < 300; const isIntersecting = xIntersecting && yIntersecting; return (

useMouse

Use a ref to add coords relative to the element
); } ``` ```javascript import * as React from "react"; import { useMouse } from "@uidotdev/usehooks"; import Demo from "./Demo"; export default function App() { const [mouse, ref] = useMouse(); const xIntersecting = mouse.elementX > 0 && mouse.elementX < 300; const yIntersecting = mouse.elementY > 0 && mouse.elementY < 300; const isIntersecting = xIntersecting && yIntersecting; return (

useMouse

Use a ref to add coords relative to the element
); } ``` -------------------------------- ### Implement a modal with useClickAway Source: https://usehooks.com/useclickaway This example demonstrates how to attach the ref returned by useClickAway to a dialog element to automatically close it when a user clicks outside the modal area. ```javascript import * as React from "react"; import { useClickAway } from "@uidotdev/usehooks"; import { closeIcon } from "./icons"; export default function App() { const [isOpen, setIsOpen] = React.useState(false); const ref = useClickAway(() => { setIsOpen(false); }); const handleOpenModal = () => { if (isOpen === false) { setIsOpen(true); } }; return ( <>

useClickAway

{isOpen && (

Modal

Click outside the modal to close (or use the button) whatever you prefer.

)} ); } ``` -------------------------------- ### Implement a Queue in React Source: https://usehooks.com/usequeue Demonstrates how to initialize a queue and use the add, remove, and clear methods to manipulate state. ```javascript import * as React from "react"; import { useQueue } from "@uidotdev/usehooks"; function QueueDemo({ first, last, size, queue }) { return (

Front

    {queue.map((item, i) => { const isFirst = first === item; const isLast = last === item; if (isFirst) { return
  • First: {item}
  • ; } if (isLast) { return
  • Last: {item}
  • ; } return
  • Item: {item}
  • ; })}

Back

{size} items in the queue
); } export default function App() { const { add, remove, clear, first, last, size, queue } = useQueue([1, 2, 3]); return (

UseQueue

); } ``` ```javascript import * as React from "react"; import { useQueue } from "@uidotdev/usehooks"; function QueueDemo({ first, last, size, queue }) { return (

Front

    {queue.map((item, i) => { const isFirst = first === item; const isLast = last === item; if (isFirst) { return
  • First: {item}
  • ; } if (isLast) { return
  • Last: {item}
  • ; } return
  • Item: {item}
  • ; })}

Back

{size} items in the queue
); } export default function App() { const { add, remove, clear, first, last, size, queue } = useQueue([1, 2, 3]); return (

UseQueue

); } ``` -------------------------------- ### Basic useIdle implementation Source: https://usehooks.com/useidle Demonstrates tracking user inactivity with a 5-second threshold and updating the UI based on the idle state. ```javascript import * as React from "react"; import { useIdle } from "@uidotdev/usehooks"; export default function App() { const idle = useIdle(5000); return (

useIdle

{idle ?

Time to move your mouse

:

Hold still and wait

}
); } ``` ```javascript import * as React from "react"; import { useIdle } from "@uidotdev/usehooks"; export default function App() { const idle = useIdle(5000); return (

useIdle

{idle ?

Time to move your mouse

:

Hold still and wait

}
); } ``` -------------------------------- ### Manage state objects with useObjectState Source: https://usehooks.com/useobjectstate Demonstrates initializing a state object and updating specific properties using the setStats function. ```javascript import * as React from "react"; import { useObjectState } from "@uidotdev/usehooks"; const initialState = { team: "Utah Jazz", wins: 2138, losses: 1789, championships: 0, }; export default function App() { const [stats, setStats] = useObjectState(initialState); const addWin = () => { setStats((s) => ({ wins: s.wins + 1, })); }; const addLoss = () => { setStats((s) => ({ losses: s.losses + 1, })); }; const reset = () => { setStats(initialState); }; return (

useObjectState

{Object.keys(stats).map((key) => { return ; })} {Object.keys(stats).map((key) => { return ; })}
{key}
{`${stats[key]}`}
); } ``` -------------------------------- ### Basic usage of useIsFirstRender Source: https://usehooks.com/useisfirstrender Demonstrates how to import and use the hook to track the initial render state within a React component. ```javascript import * as React from "react"; import { useIsFirstRender } from "@uidotdev/usehooks"; export default function App() { const isFirstRender = useIsFirstRender(); const [count, rerender] = React.useReducer((x) => x + 1, 1); return (

useIsFirstRender

First Render? {isFirstRender ? "Yes" : "No"}

Render Count: {count}

); } ``` ```javascript import * as React from "react"; import { useIsFirstRender } from "@uidotdev/usehooks"; export default function App() { const isFirstRender = useIsFirstRender(); const [count, rerender] = React.useReducer((x) => x + 1, 1); return (

useIsFirstRender

First Render? {isFirstRender ? "Yes" : "No"}

Render Count: {count}

); } ``` -------------------------------- ### Basic usage of useFetch Source: https://usehooks.com/usefetch Demonstrates fetching data from an API and managing state updates based on user interaction. ```javascript import * as React from "react"; import { useFetch } from "@uidotdev/usehooks"; import Card from "./Card"; export default function App() { const [count, setCount] = React.useState(1); const { error, data } = useFetch( `https://pokeapi.co/api/v2/pokemon/${count}` ); return (

useFetch

); } ``` -------------------------------- ### Implement useList in a React component Source: https://usehooks.com/uselist Demonstrates initializing a list and utilizing the provided methods to modify the state. ```javascript import { useList } from "@uidotdev/usehooks"; import ListDemo from "./ListDemo"; export default function App() { const [list, { set, push, removeAt, insertAt, updateAt, clear }] = useList([ "First", "Second", "Third", ]); return (

UseList

); } ``` ```javascript import { useList } from "@uidotdev/usehooks"; import ListDemo from "./ListDemo"; export default function App() { const [list, { set, push, removeAt, insertAt, updateAt, clear }] = useList([ "First", "Second", "Third", ]); return (

UseList

); } ``` -------------------------------- ### Basic usage of useIsClient Source: https://usehooks.com/useisclient Demonstrates how to import and use the useIsClient hook within a React component to conditionally render content based on the environment. ```javascript import * as React from "react"; import { useIsClient } from "@uidotdev/usehooks"; export default function App() { const isClient = useIsClient(); return (

useIsClient

Is Client?

{isClient ? "If you can see this ... you already know" : "No"}

); } ``` ```javascript import * as React from "react"; import { useIsClient } from "@uidotdev/usehooks"; export default function App() { const isClient = useIsClient(); return (

useIsClient

Is Client?

{isClient ? "If you can see this ... you already know" : "No"}

); } ``` -------------------------------- ### Implementing useLongPress in a React component Source: https://usehooks.com/uselongpress This example demonstrates how to use the useLongPress hook to trigger a modal after a 500ms press duration, including event handlers for lifecycle stages. ```javascript import * as React from "react"; import { useLongPress } from "@uidotdev/usehooks"; import { closeIcon } from "./icons"; export default function App() { const [isOpen, setIsOpen] = React.useState(false); const attrs = useLongPress( () => { setIsOpen(true); }, { onStart: (event) => console.log("Press started"), onFinish: (event) => console.log("Press Finished"), onCancel: (event) => console.log("Press cancelled"), threshold: 500, } ); return (

useLongPress

{isOpen && (

Modal

This is a modal triggered by a long press.

)}
); } ``` -------------------------------- ### Manage username availability with useSet Source: https://usehooks.com/useset Demonstrates initializing a set of usernames and using the add method to update the state based on form input. ```javascript import * as React from "react"; import { useSet } from "@uidotdev/usehooks"; function format(val) { return val.toLocaleLowerCase().replace(/\s/g, ""); } export default function App() { const [value, setValue] = React.useState(""); const set = useSet([ "benadam11", "tylermcginnis", "lynnandtonic", "alexbrown40", "uidotdev", "bytesdotdev", "reactnewsletter", ]); const handleSubmit = (e) => { e.preventDefault(); const formData = new FormData(e.target); const username = formData.get("username"); set.add(format(username)); setValue(""); e.target.reset(); e.target.focus(); }; const hasError = set.has(value); return (

useSet

Check if your username is available

@ { setValue(format(e.target.value)); }} />
{hasError && }
{Array.from(set.values()).map((username) => { const match = username === value; return ( ); })}
username {username}
); } ``` -------------------------------- ### Implement undo/redo functionality with useHistoryState Source: https://usehooks.com/usehistorystate Demonstrates managing a list of items with undo, redo, and clear capabilities. Requires the @uidotdev/usehooks package. ```javascript import * as React from "react"; import Form from "./Form"; import { useHistoryState } from "@uidotdev/usehooks"; export default function App() { const { state, set, undo, redo, clear, canUndo, canRedo } = useHistoryState({ items: [], }); const addTodo = (val) => { set({ ...state, items: state.items.concat({ id: crypto.randomUUID(), name: val }), }); }; const removeTodo = (id) => { set({ ...state, items: state.items.filter((item) => item.id !== id), }); }; return (

useHistoryState

    {state.items.map((item, index) => { return (
  • {item.name}
  • ); })}
); } ``` ```javascript import * as React from "react"; import Form from "./Form"; import { useHistoryState } from "@uidotdev/usehooks"; export default function App() { const { state, set, undo, redo, clear, canUndo, canRedo } = useHistoryState({ items: [], }); const addTodo = (val) => { set({ ...state, items: state.items.concat({ id: crypto.randomUUID(), name: val }), }); }; const removeTodo = (id) => { set({ ...state, items: state.items.filter((item) => item.id !== id), }); }; return (

useHistoryState

    {state.items.map((item, index) => { return (
  • {item.name}
  • ); })}
); } ``` -------------------------------- ### Implement useCopyToClipboard in a React component Source: https://usehooks.com/usecopytoclipboard Demonstrates how to use the hook to copy a generated hash to the clipboard and provide visual feedback. ```javascript import * as React from "react"; import { useCopyToClipboard } from "@uidotdev/usehooks"; import { copyIcon, checkIcon } from "./icons"; const randomHash = crypto.randomUUID(); export default function App() { const [copiedText, copyToClipboard] = useCopyToClipboard(); const hasCopiedText = Boolean(copiedText); return (

useCopyToClipboard

          {randomHash}
          
        
{hasCopiedText && (

Copied{" "} 🎉