Documentation for the Hooks of Yamada UI v2. # Overview ## Usage Yamada UI provides hooks in two ways. One is a new method of downloading hooks locally from [CLI](https://yamada-ui.com/docs/components/cli.md). The other is the traditional method of importing hooks from modules. ### Download The cases for downloading hooks locally from [CLI](https://yamada-ui.com/docs/components/cli.md) are as follows. - Customize the initial value or logic of the hook. - Fix a bug in the hook's logic by directly modifying it. ```bash pnpm yamada-cli add use-disclosure ``` ```bash npm yamada-cli add use-disclosure ``` ```bash yarn yamada-cli add use-disclosure ``` ```bash bun yamada-cli add use-disclosure ``` :::note Yamada UI updates the hooks, you can easily update them in the same way as [Update Components](https://yamada-ui.com/docs/components/cli.md#update-components). If your changes conflict with the updates, they will be displayed in the same way as the [HOW CONFLICTS ARE PRESENTED](https://git-scm.com/docs/git-merge#_how_conflicts_are_presented) of [Git](https://git-scm.com), and you can easily resolve them. ::: ### Import If you want to use the hook without making any changes, you can simply import the hook from the module. ```tsx import { useDisclosure } from "@yamada-ui/react" ``` ```tsx import { useDisclosure } from "@/components/ui" ``` ```tsx import { useDisclosure } from "@workspaces/ui" ``` ## Hooks Here's a list of all the hooks available in the library. - [useAnimation](https://yamada-ui.com/docs/hooks/use-animation.md) - [useAsync](https://yamada-ui.com/docs/hooks/use-async.md) - [useAsyncCallback](https://yamada-ui.com/docs/hooks/use-async-callback.md) - [useBoolean](https://yamada-ui.com/docs/hooks/use-boolean.md) - [useBreakpoint](https://yamada-ui.com/docs/hooks/use-breakpoint.md) - [useBreakpointEffect](https://yamada-ui.com/docs/hooks/use-breakpoint-effect.md) - [useBreakpointState](https://yamada-ui.com/docs/hooks/use-breakpoint-state.md) - [useBreakpointValue](https://yamada-ui.com/docs/hooks/use-breakpoint-value.md) - [useClipboard](https://yamada-ui.com/docs/hooks/use-clipboard.md) - [useColorMode](https://yamada-ui.com/docs/hooks/use-color-mode.md) - [useColorModeValue](https://yamada-ui.com/docs/hooks/use-color-mode-value.md) - [useCounter](https://yamada-ui.com/docs/hooks/use-counter.md) - [useDescendants](https://yamada-ui.com/docs/hooks/use-descendants.md) - [useDisclosure](https://yamada-ui.com/docs/hooks/use-disclosure.md) - [useDynamicAnimation](https://yamada-ui.com/docs/hooks/use-dynamic-animation.md) - [useEyeDropper](https://yamada-ui.com/docs/hooks/use-eye-dropper.md) - [useFocusOnShow](https://yamada-ui.com/docs/hooks/use-focus-on-show.md) - [useFormatByte](https://yamada-ui.com/docs/hooks/use-format-byte.md) - [useFormatDateTime](https://yamada-ui.com/docs/hooks/use-format-date-time.md) - [useFormatNumber](https://yamada-ui.com/docs/hooks/use-format-number.md) - [useHover](https://yamada-ui.com/docs/hooks/use-hover.md) - [useIdle](https://yamada-ui.com/docs/hooks/use-idle.md) - [useInfiniteScroll](https://yamada-ui.com/docs/hooks/use-infinite-scroll.md) - [useInterval](https://yamada-ui.com/docs/hooks/use-interval.md) - [useLoading](https://yamada-ui.com/docs/hooks/use-loading.md) - [useLocalStorage](https://yamada-ui.com/docs/hooks/use-local-storage.md) - [useMediaQuery](https://yamada-ui.com/docs/hooks/use-media-query.md) - [useNotice](https://yamada-ui.com/docs/hooks/use-notice.md) - [useOs](https://yamada-ui.com/docs/hooks/use-os.md) - [useOutsideClick](https://yamada-ui.com/docs/hooks/use-outside-click.md) - [usePrevious](https://yamada-ui.com/docs/hooks/use-previous.md) - [useProcessing](https://yamada-ui.com/docs/hooks/use-processing.md) - [usePromiseDisclosure](https://yamada-ui.com/docs/hooks/use-promise-disclosure.md) - [useResizeObserver](https://yamada-ui.com/docs/hooks/use-resize-observer.md) - [useTheme](https://yamada-ui.com/docs/hooks/use-theme.md) - [useTimeout](https://yamada-ui.com/docs/hooks/use-timeout.md) - [useUpdateBreakpointEffect](https://yamada-ui.com/docs/hooks/use-update-breakpoint-effect.md) - [useUpdateEffect](https://yamada-ui.com/docs/hooks/use-update-effect.md) - [useValue](https://yamada-ui.com/docs/hooks/use-value.md) - [useWindowEvent](https://yamada-ui.com/docs/hooks/use-window-event.md) # useAnimation ```tsx const animation = useAnimation({ keyframes: { "0%": { bg: "red.500", }, "20%": { bg: "green.500", }, "40%": { bg: "purple.500", }, "60%": { bg: "yellow.500", }, "80%": { bg: "blue.500", }, "100%": { bg: "red.500", }, }, duration: "10s", iterationCount: "infinite", timingFunction: "linear", }) return ``` ## Usage ```tsx import { useAnimation } from "@yamada-ui/react" ``` ```tsx import { useAnimation } from "@/components/ui" ``` ```tsx import { useAnimation } from "@workspaces/ui" ``` ```tsx const animation = useAnimation() ``` ### Use Theme Tokens To use [theme](https://yamada-ui.com/docs/theming.md) [animations](https://yamada-ui.com/docs/theming/tokens/animations.md), set the argument. ```tsx const animation = useAnimation("gradient") return ``` :::warning By default, no animation tokens are defined. ::: ### Use Multiple Animations To use multiple animations, set the arguments as an array. ```tsx const animation = useAnimation([ { keyframes: { "0%": { bg: "red.500", }, "20%": { bg: "green.500", }, "40%": { bg: "purple.500", }, "60%": { bg: "yellow.500", }, "80%": { bg: "blue.500", }, "100%": { bg: "red.500", }, }, duration: "10s", iterationCount: "infinite", timingFunction: "linear", }, { keyframes: { "0%": { h: "xs", }, "50%": { h: "md", }, "100%": { h: "xs", }, }, duration: "10s", iterationCount: "infinite", timingFunction: "linear", }, { keyframes: { "0%": { w: "full", }, "50%": { w: "50%", }, "100%": { w: "full", }, }, duration: "10s", iterationCount: "infinite", timingFunction: "linear", }, ]) return ( ) ``` ### Use Responsive Design To use responsive design, set the `animation` as a object. ```tsx const desktopAnimation = useAnimation({ keyframes: { "0%": { bg: "red.500", }, "20%": { bg: "green.500", }, "40%": { bg: "purple.500", }, "60%": { bg: "yellow.500", }, "80%": { bg: "blue.500", }, "100%": { bg: "red.500", }, }, duration: "10s", iterationCount: "infinite", timingFunction: "linear", }) const tabletAnimation = useAnimation({ keyframes: { "0%": { bg: "cyan.500", }, "20%": { bg: "emerald.500", }, "40%": { bg: "pink.500", }, "60%": { bg: "amber.500", }, "80%": { bg: "sky.500", }, "100%": { bg: "cyan.500", }, }, duration: "10s", iterationCount: "infinite", timingFunction: "linear", }) return ( ) ``` ### Use Color Mode To use color mode, pass an array to `animation`. ```tsx const lightAnimation = useAnimation({ keyframes: { "0%": { bg: "red.500", }, "20%": { bg: "green.500", }, "40%": { bg: "purple.500", }, "60%": { bg: "yellow.500", }, "80%": { bg: "blue.500", }, "100%": { bg: "red.500", }, }, duration: "10s", iterationCount: "infinite", timingFunction: "linear", }) const darkAnimation = useAnimation({ keyframes: { "0%": { bg: "red.800", }, "20%": { bg: "green.800", }, "40%": { bg: "purple.800", }, "60%": { bg: "yellow.800", }, "80%": { bg: "blue.800", }, "100%": { bg: "red.800", }, }, duration: "10s", iterationCount: "infinite", timingFunction: "linear", }) return ``` # useAsyncCallback ```tsx const [loading, onClick] = useAsyncCallback(async () => { await wait(3000) }, []) return ( ) ``` ## Usage ```tsx import { useAsyncCallback } from "@yamada-ui/react" ``` ```tsx import { useAsyncCallback } from "@/components/ui" ``` ```tsx import { useAsyncCallback } from "@workspaces/ui" ``` ```tsx const [loading, onClick] = useAsyncCallback(async () => {}, []) ``` ### Use loading When using loading, set `loading` to `screen` or `page` etc. ```tsx const [loading, onClick] = useAsyncCallback( async () => { await wait(3000) }, [], { loading: "page" }, ) return ( ) ``` ### Disable processing When disabling processing, set `processing` to `false`. ```tsx const [, onClick] = useAsyncCallback( async () => { await wait(3000) }, [], { loading: "page", processing: false }, ) return ``` # useAsync ```tsx const [flg, { toggle }] = useBoolean() const { value, error, loading } = useAsync( async () => new Promise((resolve, reject) => { setTimeout(() => { if (Math.random() > 0.5) { resolve("Succeeded.") } else { reject(new Error("A pseudo random error occurred.")) } }, 3000) }), [flg], ) return ( {loading ? ( Loading... ) : error ? ( Error: {error.message} ) : ( Value: {value} )} ) ``` ## Usage ```tsx import { useAsync } from "@yamada-ui/react" ``` ```tsx import { useAsync } from "@/components/ui" ``` ```tsx import { useAsync } from "@workspaces/ui" ``` ```tsx const { value, error, loading } = useAsync(async () => {}, []) ``` # useBoolean ```tsx const [flg, { on, off, toggle }] = useBoolean() return ( state: {String(flg)} On Off Toggle ) ``` ## Usage ```tsx import { useBoolean } from "@yamada-ui/react" ``` ```tsx import { useBoolean } from "@/components/ui" ``` ```tsx import { useBoolean } from "@workspaces/ui" ``` ```tsx const [flg, { on, off, toggle }] = useBoolean() ``` ### Using Initial Values ```tsx const [flg, { on, off, toggle }] = useBoolean(true) return ( state: {String(flg)} On Off Toggle ) ``` # useBreakpointEffect ```tsx const [device, setDevice] = useState("mobile"); useBreakpointEffect(breakpoint => { if (breakpoint === "sm") { setDevice("mobile"); } else if (breakpoint === "md") { setDevice("tablet"); } else { setDevice("desktop"); } }, []); return The current device is "{device}"; ``` ## Usage ```tsx import { useBreakpointEffect } from "@yamada-ui/react" ``` ```tsx import { useBreakpointEffect } from "@/components/ui" ``` ```tsx import { useBreakpointEffect } from "@workspaces/ui" ``` ```tsx const [device, setDevice] = useState("mobile") useBreakpointEffect((breakpoint) => { if (breakpoint === "sm") { setDevice("mobile") } else if (breakpoint === "md") { setDevice("tablet") } else { setDevice("desktop") } }, []) ``` # useBreakpointState ```tsx const [value, setValue] = useBreakpointState({ base: 1, md: 2 }) return ( ) ``` ## Usage ```tsx import { useBreakpointState } from "@yamada-ui/react" ``` ```tsx import { useBreakpointState } from "@/components/ui" ``` ```tsx import { useBreakpointState } from "@workspaces/ui" ``` ```tsx const [value, setValue] = useBreakpointState({ base: 1, md: 2 }) ``` # useBreakpointValue ```tsx const breakpoint = useBreakpoint() const bg = useBreakpointValue({ base: "red.500", sm: "purple.500", md: "yellow.500", lg: "green.500", xl: "blue.500", "2xl": "pink.500", }) return ( The current breakpoint is "{breakpoint}" ) ``` ## Usage ```tsx import { useBreakpointValue } from "@yamada-ui/react" ``` ```tsx import { useBreakpointValue } from "@/components/ui" ``` ```tsx import { useBreakpointValue } from "@workspaces/ui" ``` ```tsx const bg = useBreakpointValue({ base: "red.500", sm: "purple.500", md: "yellow.500", lg: "green.500", xl: "blue.500", "2xl": "pink.500", }) ``` # useBreakpoint ```tsx const breakpoint = useBreakpoint() return The current breakpoint is "{breakpoint}". ``` ## Usage ```tsx import { useBreakpoint } from "@yamada-ui/react" ``` ```tsx import { useBreakpoint } from "@/components/ui" ``` ```tsx import { useBreakpoint } from "@workspaces/ui" ``` ```tsx const breakpoint = useBreakpoint() ``` :::note The return value refers to the [breakpoint](https://yamada-ui.com/docs/theming/breakpoints.md) of the theme. ::: # useClipboard ```tsx const { onCopy, value, setValue, copied } = useClipboard() return ( setValue(e.target.value)} /> ) ``` ## Usage ```tsx import { useClipboard } from "@yamada-ui/react" ``` ```tsx import { useClipboard } from "@/components/ui" ``` ```tsx import { useClipboard } from "@workspaces/ui" ``` ```tsx const { onCopy, value, setValue, copied } = useClipboard("initial value") ``` ### Using Initial Values ```tsx const { onCopy, value, setValue, copied } = useClipboard("initial value") return ( setValue(e.target.value)} /> ) ``` ### Change Timeout To change the timeout, set a number(milliseconds) to the second argument. The default is `1500`. ```tsx const { onCopy, value, setValue, copied } = useClipboard("", 5000) return ( setValue(e.target.value)} /> ) ``` ### Copy the Specified Value ```tsx const { onCopy, copied } = useClipboard() const value = "Read-Only Value" return ( ) ``` # useColorModeValue ```tsx const { colorMode } = useColorMode() const color = useColorModeValue("green", "red") return The current colorMode is "{colorMode}" ``` ## Usage ```tsx import { useColorModeValue } from "@yamada-ui/react" ``` ```tsx import { useColorModeValue } from "@/components/ui" ``` ```tsx import { useColorModeValue } from "@workspaces/ui" ``` ```tsx const color = useColorModeValue("green", "red") ``` :::tip Color Mode overview is [here](https://yamada-ui.com/docs/styling/color-mode.md). ::: # useColorMode ```tsx const { colorMode } = useColorMode() return The current colorMode is "{colorMode}" ``` ## Usage ```tsx import { useColorMode } from "@yamada-ui/react" ``` ```tsx import { useColorMode } from "@/components/ui" ``` ```tsx import { useColorMode } from "@workspaces/ui" ``` ```tsx const { changeColorMode, colorMode, internalColorMode, toggleColorMode } = useColorMode() ``` :::tip Color Mode overview is [here](https://yamada-ui.com/docs/styling/color-mode.md). ::: ### Switching Color Mode - `colorMode`: Provides the current color mode. - `internalColorMode`: Provides the current color mode including `system`. ```tsx const { colorMode, internalColorMode, changeColorMode, toggleColorMode } = useColorMode() return ( The current colorMode is "{colorMode}", internal colorMode is " {internalColorMode}" ) ``` # useCounter ```tsx const { value, increment, decrement, reset } = useCounter({ defaultValue: 10, }) return ( Count: {value} increment()} > + 1 decrement()} > - 1 Reset ) ``` ## Usage ```tsx import { useCounter } from "@yamada-ui/react" ``` ```tsx import { useCounter } from "@/components/ui" ``` ```tsx import { useCounter } from "@workspaces/ui" ``` ```tsx const { value, valueAsNumber, update, increment, decrement, reset, cast, out } = useCounter() ``` ### Set Default Value To set a default value, pass a number or string to `defaultValue`. ```tsx const { value, increment, decrement, reset } = useCounter({ defaultValue: 10, }) return ( Count: {value} increment()} > + 1 decrement()} > - 1 Reset ) ``` ### Set Min And Max Values To set minimum and maximum values, set `min` or `max` to a number. ```tsx const { value, increment, decrement, min, max, reset } = useCounter({ defaultValue: 5, min: 0, max: 10, }) return ( Count: {value} increment()} disabled={max} > + 1 decrement()} disabled={min} > - 1 Reset ) ``` ### Set Step Value To set a step value, pass a number to `step`. ```tsx const { value, increment, decrement, reset } = useCounter({ defaultValue: 0, step: 5, }) return ( Count: {value} increment()} > + 5 decrement()} > - 5 Reset ) ``` ```tsx const { value, increment, decrement } = useCounter({ defaultValue: 0, }) return ( Count: {value} {(step) => ( increment(step)}> + {step} )} {(step) => ( decrement(step)}> - {step} )} ) ``` ### Specify Precision To specify precision, pass a number to `precision`. ```tsx const { value, increment, decrement, reset } = useCounter({ defaultValue: 5.123, step: 0.1, precision: 2, }) return ( Count: {value} increment()} > + 0.1 decrement()} > - 0.1 Reset ) ``` ### Allow Out Of Range Values To allow out of range values, set `keepWithinRange` to `false`. The `out` property is also provided to indicate whether the value is out of range. ```tsx const { value, increment, decrement, out, reset } = useCounter({ defaultValue: 5, min: 0, max: 10, keepWithinRange: false, }) return ( Count: {value} {out ? "(Out Of Range)" : ""} increment()} > + 1 decrement()} > - 1 Reset ) ``` ### Cast Value To cast value, use the `cast` function. ```tsx const { value, setValue, cast } = useCounter({ defaultValue: 0, precision: 2, }) return ( setValue(e.target.value)} onBlur={(e) => cast(e.target.value)} /> ) ``` # useDescendants ```tsx const { useDescendants, useDescendant, DescendantsContext } = createDescendants() const ref = useRef(null) const descendants = useDescendants() const onFocus = useCallback( (ev: FocusEvent) => { if (ev.target !== ref.current) return const descendant = descendants.enabledFirstValue() if (descendant) { descendant.node.focus() if (ref.current) ref.current.tabIndex = -1 } }, [descendants], ) const onBlur = useCallback((ev: FocusEvent) => { if (contains(ref.current, ev.relatedTarget)) return if (ref.current) ref.current.tabIndex = 0 }, []) const Item: FC<{ index: number }> = ({ index }) => { const { descendants, register } = useDescendant() const onKeyDown = useCallback( (ev: KeyboardEvent) => { runKeyAction(ev, { ArrowDown: () => { const descendant = descendants.enabledNextValue(index) if (descendant) descendant.node.focus() }, ArrowUp: () => { const descendant = descendants.enabledPrevValue(index) if (descendant) descendant.node.focus() }, Home: () => { const descendant = descendants.enabledFirstValue() if (descendant) descendant.node.focus() }, End: () => { const descendant = descendants.enabledLastValue() if (descendant) descendant.node.focus() }, }) }, [descendants], ) return (
Item {index}
) } return ( {Array.from({ length: 5 }).map((_, index) => ( ))} ) ``` ## Usage ```tsx import { createDescendants } from "@yamada-ui/react" ``` ```tsx import { createDescendants } from "@/components/ui" ``` ```tsx import { createDescendants } from "@workspaces/ui" ``` ```tsx const { DescendantsContext, useDescendant, useDescendantRegister, useDescendants, useDescendantsContext, } = createDescendants() ``` ```tsx const descendants = useDescendants() ``` ```tsx const { descendants, register } = useDescendant() ``` ### Disable descendant To disable a descendant, set the `disabled` prop to `true` on `useDescendant`. ```tsx const { useDescendants, useDescendant, DescendantsContext } = createDescendants() const ref = useRef(null) const descendants = useDescendants() const onFocus = useCallback( (ev: FocusEvent) => { if (ev.target !== ref.current) return const descendant = descendants.enabledFirstValue() if (descendant) { descendant.node.focus() if (ref.current) ref.current.tabIndex = -1 } }, [descendants], ) const onBlur = useCallback((ev: FocusEvent) => { if (contains(ref.current, ev.relatedTarget)) return if (ref.current) ref.current.tabIndex = 0 }, []) const Item: FC<{ index: number; disabled?: boolean }> = ({ index, disabled, }) => { const { descendants, register } = useDescendant({ disabled }) const onKeyDown = useCallback( (ev: KeyboardEvent) => { runKeyAction(ev, { ArrowDown: () => { const descendant = descendants.enabledNextValue(index) if (descendant) descendant.node.focus() }, ArrowUp: () => { const descendant = descendants.enabledPrevValue(index) if (descendant) descendant.node.focus() }, Home: () => { const descendant = descendants.enabledFirstValue() if (descendant) descendant.node.focus() }, End: () => { const descendant = descendants.enabledLastValue() if (descendant) descendant.node.focus() }, }) }, [descendants], ) return (
Item {index}
) } return ( {Array.from({ length: 5 }).map((_, index) => ( ))} ) ``` # useDisclosure ```tsx const { open, onOpen, onClose } = useDisclosure() return ( <> ) ``` ## Usage ```tsx import { useDisclosure } from "@yamada-ui/react" ``` ```tsx import { useDisclosure } from "@/components/ui" ``` ```tsx import { useDisclosure } from "@workspaces/ui" ``` ```tsx const { open, onOpen, onClose, onToggle } = useDisclosure() ``` ### Using Callback Functions To use callback functions, assign a function to `onOpen` or `onClose`. This is useful for executing APIs or other logic before opening components such as [Modal](https://yamada-ui.com/docs/components/modal.md). ```tsx const { open, onClose, onOpen } = useDisclosure({ onClose: (value) => { console.log("onClose:", value) }, onOpen: (value) => { console.log("onOpen:", value) }, }) return ( <> onClose("This is arg")} onClose={() => onClose("This is arg")} onSuccess={() => onClose("This is arg")} /> ) ``` By default, the callback functions are executed before `onOpen` or `onClose`. If you want the callbacks to be executed after `onOpen` or `onClose`, set the `timing` option to `"after"`. ```tsx const { open, onClose, onOpen } = useDisclosure({ onClose: (value) => { console.log("onClose:", value) }, onOpen: (value) => { console.log("onOpen:", value) }, timing: "after", }) return ( <> onClose("This is arg")} onClose={() => onClose("This is arg")} onSuccess={() => onClose("This is arg")} /> ) ``` # useDynamicAnimation ```tsx const [animation, setAnimation] = useDynamicAnimation({ moveLeft: { duration: "moderate", fillMode: "forwards", keyframes: { "0%": { transform: "translateX(100%)" }, "100%": { transform: "translateX(0%)" }, }, timingFunction: "ease-in-out", }, moveRight: { duration: "moderate", fillMode: "forwards", keyframes: { "0%": { transform: "translateX(0%)" }, "100%": { transform: "translateX(100%)" }, }, timingFunction: "ease-in-out", }, }) return ( Box ) ``` ## Usage ```tsx import { useDynamicAnimation } from "@yamada-ui/react" ``` ```tsx import { useDynamicAnimation } from "@/components/ui" ``` ```tsx import { useDynamicAnimation } from "@workspaces/ui" ``` ```tsx const [animation, setAnimation] = useDynamicAnimation() ``` ### Use Theme Tokens To use [theme](https://yamada-ui.com/docs/theming.md) [animations](https://yamada-ui.com/docs/theming/tokens/animations.md), set the keys as the animation names. ```tsx const [animation, setAnimation] = useDynamicAnimation({ slideToLeft: "slide-to-right-full-reverse", slideToRight: "slide-to-right-full", }) return ( Box ) ``` :::warning By default, no animation tokens are defined. ::: ### Use Multiple Animations To use multiple animations, pass an object with the keys as the animation names. ```tsx const [animation, setAnimation] = useDynamicAnimation({ moveLeft: [ { duration: "moderate", fillMode: "forwards", keyframes: { "0%": { transform: "translateX(100%)" }, "100%": { transform: "translateX(0%)" }, }, timingFunction: "ease-in-out", }, { duration: "moderate", fillMode: "forwards", keyframes: { "0%": { bg: "green" }, "100%": { bg: "orange" }, }, timingFunction: "ease-in-out", }, ], moveRight: [ { duration: "moderate", fillMode: "forwards", keyframes: { "0%": { transform: "translateX(0%)" }, "100%": { transform: "translateX(100%)" }, }, timingFunction: "ease-in-out", }, { duration: "moderate", fillMode: "forwards", keyframes: { "0%": { bg: "orange" }, "100%": { bg: "green" }, }, timingFunction: "ease-in-out", }, ], }) return ( Box ) ``` # useEyeDropper ```tsx const { supported, onOpen } = useEyeDropper() const [color, setColor] = useState("#FF0000") const onClick = async () => { const result = await onOpen() if (result) setColor(result.sRGBHex) } return ( {color} EyeDropper API is not supported in this browser. ) ``` ## Usage ```tsx import { useEyeDropper } from "@yamada-ui/react" ``` ```tsx import { useEyeDropper } from "@/components/ui" ``` ```tsx import { useEyeDropper } from "@workspaces/ui" ``` ```tsx const { supported, onOpen } = useEyeDropper() ``` # useFocusOnShow ```tsx const [visible, setVisible] = useState(false) const ref = useRef(null) const inputRef = useRef(null) useFocusOnShow(ref, { focusTarget: inputRef, visible, shouldFocus: true, }) return ( ) ``` ## Usage ```tsx import { useFocusOnShow } from "@yamada-ui/react" ``` ```tsx import { useFocusOnShow } from "@/components/ui" ``` ```tsx import { useFocusOnShow } from "@workspaces/ui" ``` ```tsx const ref = useRef(null) const focusTargetRef = useRef(null) useFocusOnShow(ref, { focusTarget: focusTargetRef, visible: true, shouldFocus: true, }) ``` # useFormatByte ```tsx const kilobyte = useFormatByte(1024) const megabyte = useFormatByte(1024 * 1024) const gigabyte = useFormatByte(1024 * 1024 * 1024) const terabyte = useFormatByte(1024 * 1024 * 1024 * 1024) return ( <> {kilobyte} {megabyte} {gigabyte} {terabyte} ) ``` ## Usage ```tsx import { useFormatByte } from "@yamada-ui/react" ``` ```tsx import { useFormatByte } from "@/components/ui" ``` ```tsx import { useFormatByte } from "@workspaces/ui" ``` ```tsx const kilobyte = useFormatByte(1024) ``` :::note `FormatByte` automatically selects the most appropriate unit (`byte`, `kB`, `MB`, `GB`, `TB`) based on the byte value size. ::: :::note `useFormatByte` internally uses [Intl.NumberFormat](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat). ::: ### Changing the Locale To change the locale, set a value for [locale](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#locales). ```tsx const enByte = useFormatByte(1024, { locale: "en-US" }) const jaByte = useFormatByte(1024, { locale: "ja-JP" }) const deByte = useFormatByte(1024, { locale: "de-DE" }) return ( en-US {enByte} ja-JP {jaByte} de-DE {deByte} ) ``` ### Set the Locale for the Entire Application If you want to set the locale for the entire application, set the `locale` for the `UIProvider`. ```tsx import { UIProvider } from "@yamada-ui/react" const App = () => { return ( ) } ``` ### Unit Format To convert units, set `unit` to either `"byte"` or `"bit"`. The default is `"byte"`. ```tsx const bytes = useFormatByte(1024, { unit: "byte" }) const bits = useFormatByte(1024, { unit: "bit" }) return ( Bytes {bytes} Bits {bits} ) ``` ### Unit Display To change the unit display, set a value for [unitDisplay](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#unitdisplay). ```tsx const short = useFormatByte(1024, { unitDisplay: "short" }) const narrow = useFormatByte(1024, { unitDisplay: "narrow" }) const long = useFormatByte(1024, { unitDisplay: "long" }) return ( Short {short} Narrow {narrow} Long {long} ) ``` # useFormatDateTime ```tsx const formattedValue = useFormatDateTime(new Date()) return {formattedValue} ``` ## Usage ```tsx import { useFormatDateTime } from "@yamada-ui/react" ``` ```tsx import { useFormatDateTime } from "@/components/ui" ``` ```tsx import { useFormatDateTime } from "@workspaces/ui" ``` ```tsx const formattedValue = useFormatDateTime(new Date()) ``` It formats date time according to the specified locale and options. The hook returns the formatted value directly. :::note `useFormatDateTime` internally uses [Intl.DateTimeFormat](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat). ::: ### Changing the Locale To change the locale, set a value for [locale](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat#locales). ```tsx const enValue = useFormatDateTime(new Date(), { locale: "en-US" }) const jaValue = useFormatDateTime(new Date(), { locale: "ja-JP" }) const deValue = useFormatDateTime(new Date(), { locale: "de-DE" }) const frValue = useFormatDateTime(new Date(), { locale: "fr-FR" }) const zhValue = useFormatDateTime(new Date(), { locale: "zh-CN" }) return ( en-US {enValue} ja-JP {jaValue} de-DE {deValue} fr-FR {frValue} zh-CN {zhValue} ) ``` ### Set the Locale for the Entire Application If you want to set the locale for the entire application, set the `locale` for the `UIProvider`. ```tsx import { UIProvider } from "@yamada-ui/react" const App = () => { return ( ) } ``` ### Converting to Year To convert to year, set a value for [year](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat#year). ```tsx const formattedValue = useFormatDateTime(new Date(), { year: "numeric" }) return {formattedValue} ``` ### Converting to Month To convert to month, set a value for [month](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat#month). ```tsx const formattedValue = useFormatDateTime(new Date(), { month: "long" }) return {formattedValue} ``` ### Converting to Day To convert to day, set a value for [day](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat#day). ```tsx const formattedValue = useFormatDateTime(new Date(), { day: "2-digit" }) return {formattedValue} ``` ### Converting to Weekday To convert to weekday, set a value for [weekday](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat#weekday). ```tsx const formattedValue = useFormatDateTime(new Date(), { weekday: "long" }) return {formattedValue} ``` # useFormatNumber ```tsx const formattedValue = useFormatNumber(1234567.89) return {formattedValue} ``` ## Usage ```tsx import { useFormatNumber } from "@yamada-ui/react" ``` ```tsx import { useFormatNumber } from "@/components/ui" ``` ```tsx import { useFormatNumber } from "@workspaces/ui" ``` ```tsx const formattedValue = useFormatNumber(1234567.89) ``` It formats numbers according to the specified locale and options. The hook returns the formatted value directly. :::note `useFormatNumber` internally uses [Intl.NumberFormat](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat). ::: ### Changing the Locale To change the locale, set a value for [locale](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#locales). ```tsx const enValue = useFormatNumber(1234567.89, { locale: "en-US" }) const jaValue = useFormatNumber(1234567.89, { locale: "ja-JP" }) const deValue = useFormatNumber(1234567.89, { locale: "de-DE" }) const frValue = useFormatNumber(1234567.89, { locale: "fr-FR" }) const zhValue = useFormatNumber(1234567.89, { locale: "zh-CN" }) return ( en-US {enValue} ja-JP {jaValue} de-DE {deValue} fr-FR {frValue} zh-CN {zhValue} ) ``` ### Set the Locale for the Entire Application If you want to set the locale for the entire application, set the `locale` for the `UIProvider`. ```tsx import { UIProvider } from "@yamada-ui/react" const App = () => { return ( ) } ``` ### Converting to Currency To convert to currency, set `"currency"` for [style](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#style). ```tsx const usdValue = useFormatNumber(1234567.89, { style: "currency", currency: "USD", locale: "en-US", }) const eurValue = useFormatNumber(1234567.89, { style: "currency", currency: "EUR", locale: "de-DE", }) const jpyValue = useFormatNumber(1234567.89, { style: "currency", currency: "JPY", locale: "ja-JP", }) return ( USD {usdValue} EUR {eurValue} JPY {jpyValue} ) ``` ### Converting to Units To convert to units, set `"unit"` for [style](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#style). ```tsx const kilogramValue = useFormatNumber(100, { style: "unit", unit: "kilogram", }) const celsiusValue = useFormatNumber(100, { style: "unit", unit: "celsius", unitDisplay: "long", }) const speedValue = useFormatNumber(100, { style: "unit", unit: "kilometer-per-hour", unitDisplay: "narrow", }) return ( {kilogramValue} {celsiusValue} {speedValue} ) ``` ### Converting to Percent To convert to percent, set `"percent"` for [style](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#style). ```tsx const percent1Value = useFormatNumber(0.45, { style: "percent" }) const percent2Value = useFormatNumber(0.45, { style: "percent", minimumFractionDigits: 2, }) return ( {percent1Value} {percent2Value} ) ``` ### Converting Notation To convert notation, set a value for [notation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#notation). ```tsx const standardValue = useFormatNumber(1234567.89, { notation: "standard" }) const scientificValue = useFormatNumber(1234567.89, { notation: "scientific" }) const engineeringValue = useFormatNumber(1234567.89, { notation: "engineering", }) const compactValue = useFormatNumber(1234567.89, { notation: "compact" }) return ( {standardValue} {scientificValue} {engineeringValue} {compactValue} ) ``` ### Controlling Decimal Places To control the number of decimal places, use [minimumFractionDigits](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#minimumfractiondigits) and [maximumFractionDigits](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#maximumfractiondigits). ```tsx const fixed2Value = useFormatNumber(1234.5, { minimumFractionDigits: 2, maximumFractionDigits: 2, }) const range03Value = useFormatNumber(1234.567, { minimumFractionDigits: 0, maximumFractionDigits: 3, }) const fixed4Value = useFormatNumber(1234, { minimumFractionDigits: 4, maximumFractionDigits: 4, }) return ( {fixed2Value} {range03Value} {fixed4Value} ) ``` ### Disabling Grouping To disable grouping, set `false` for [useGrouping](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#usegrouping). ```tsx const noGroupingValue = useFormatNumber(1234567.89, { useGrouping: false }) return {noGroupingValue} ``` ### Changing the Sign Display To change the sign display, set a value for [signDisplay](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#signdisplay). ```tsx const alwaysValue = useFormatNumber(1234.5, { signDisplay: "always" }) const exceptZeroValue = useFormatNumber(-1234.5, { signDisplay: "exceptZero" }) return ( {alwaysValue} {exceptZeroValue} ) ``` # useHover ```tsx const { hovered, ref } = useHover() return ( {hovered ? "I am hovered" : "Put mouse over me please"} ) ``` ## Usage ```tsx import { useHover } from "@yamada-ui/react" ``` ```tsx import { useHover } from "@/components/ui" ``` ```tsx import { useHover } from "@workspaces/ui" ``` ```tsx const { hovered, ref } = useHover() ``` # useIdle ```tsx const idle = useIdle(2000) return Current state: {idle ? "idle" : "not idle"} ``` ## Usage ```tsx import { useIdle } from "@yamada-ui/react" ``` ```tsx import { useIdle } from "@/components/ui" ``` ```tsx import { useIdle } from "@workspaces/ui" ``` ```tsx const idle = useIdle(2000) ``` # useInfiniteScroll ```tsx const [count, setCount] = useState(50) const { ref, finish } = useInfiniteScroll({ onLoad: ({ finish, index }) => { console.log("onLoad", index) setCount((prev) => prev + 50) if (index >= 5) finish() }, }) return ( {Array(count) .fill(0) .map((_, index) => ( 天元突破グレンラガン いいか、忘れんな。お前を信じろ。俺が信じるお前でもない。お前が信じる俺でもない。お前が信じる…お前を信じろ! ))} {!finish ? (
) : null}
) ``` ## Usage ```tsx import { useInfiniteScroll } from "@yamada-ui/react" ``` ```tsx import { useInfiniteScroll } from "@/components/ui" ``` ```tsx import { useInfiniteScroll } from "@workspace/ui" ``` ```tsx const { ref, finish } = useInfiniteScroll() ``` ### Specify the Viewport To specify the viewport, set a `ref` to `rootRef`. :::note If `rootRef` is not set, the browser's viewport will be used. ::: ```tsx const rootRef = useRef(null) const resetRef = useRef<() => void>(noop) const [count, setCount] = useState(50) const { ref, finish } = useInfiniteScroll({ resetRef, rootRef, onLoad: ({ finish, index }) => { console.log("onLoad", index) setCount((prev) => prev + 50) if (index >= 5) finish() }, }) return ( {Array(count) .fill(0) .map((_, index) => ( 天元突破グレンラガン いいか、忘れんな。お前を信じろ。俺が信じるお前でもない。お前が信じる俺でもない。お前が信じる…お前を信じろ! ))} {!finish ? (
) : null}
) ``` ### Set rootMargin To set [rootMargin](https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API#rootmargin), assign a string to rootMargin. ```tsx const [count, setCount] = useState(50) const { ref, finish } = useInfiniteScroll({ rootMargin: "300px 0px 0px 0px", onLoad: ({ finish, index }) => { console.log("onLoad", index) setCount((prev) => prev + 50) if (index >= 5) finish() }, }) return ( {Array(count) .fill(0) .map((_, index) => ( 天元突破グレンラガン いいか、忘れんな。お前を信じろ。俺が信じるお前でもない。お前が信じる俺でもない。お前が信じる…お前を信じろ! ))} {!finish ? (
) : null}
) ``` ### Set threshold To set [threshold](https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API#threshold), assign a number to `threshold`. ```tsx const [count, setCount] = useState(50) const { ref, finish } = useInfiniteScroll({ threshold: 1, onLoad: ({ finish, index }) => { console.log("onLoad", index) setCount((prev) => prev + 50) if (index >= 5) finish() }, }) return ( {Array(count) .fill(0) .map((_, index) => ( 天元突破グレンラガン いいか、忘れんな。お前を信じろ。俺が信じるお前でもない。お前が信じる俺でもない。お前が信じる…お前を信じろ! ))} {!finish ? (
) : null}
) ``` ### Initial Load To load initially, set `initialLoad` to `true`. By default, `initialLoad` is set to `false`, and the initial(`index=0`) `onLoad` is not executed. `true`: The first `onLoad` is executed regardless of the scroll amount, and the provided `index` starts from `0`.\ `false`: `onLoad` is executed when a certain scroll is reached, and the provided `index` starts from `1`. ```tsx const [count, setCount] = useState(50) const { ref, finish } = useInfiniteScroll({ initialLoad: true, onLoad: ({ finish, index }) => { console.log("onLoad", index) setCount((prev) => prev + 50) if (index >= 5) finish() }, }) return ( {Array(count) .fill(0) .map((_, index) => ( 天元突破グレンラガン いいか、忘れんな。お前を信じろ。俺が信じるお前でもない。お前が信じる俺でもない。お前が信じる…お前を信じろ! ))} {!finish ? (
) : null}
) ``` ### Change the Starting index To change the starting index, set a number to `startIndex`. The default is `1`. ```tsx const [count, setCount] = useState(50) const { ref, finish } = useInfiniteScroll({ startIndex: 3, onLoad: ({ finish, index }) => { console.log("onLoad", index) setCount((prev) => prev + 50) if (index >= 5) finish() }, }) return ( {Array(count) .fill(0) .map((_, index) => ( 天元突破グレンラガン いいか、忘れんな。お前を信じろ。俺が信じるお前でもない。お前が信じる俺でもない。お前が信じる…お前を信じろ! ))} {!finish ? (
) : null}
) ``` ### Reverse To reverse, set `reverse` to `true`. The default is `false`. ```tsx const rootRef = useRef(null) const [count, setCount] = useState(50) const { ref, finish } = useInfiniteScroll({ reverse: true, rootRef, onLoad: ({ finish, index }) => { console.log("onLoad", index) setCount((prev) => prev + 50) if (index >= 5) finish() }, }) return ( {!finish ? (
) : null} {Array(count) .fill(0) .map((_, index) => ( 天元突破グレンラガン いいか、忘れんな。お前を信じろ。俺が信じるお前でもない。お前が信じる俺でもない。お前が信じる…お前を信じろ! ))}
) ``` # useInterval ```tsx const [state, setState] = useState(1) useInterval(() => setState((prev) => prev + 1), 3000) return Current state: {state} ``` ## Usage ```tsx import { useInterval } from "@yamada-ui/react" ``` ```tsx import { useInterval } from "@/components/ui" ``` ```tsx import { useInterval } from "@workspaces/ui" ``` ```tsx const [state, setState] = useState(1) useInterval(() => setState((prev) => prev + 1), 3000) ``` # useLoading ```tsx const { screen, page, background } = useLoading() const onLoadingScreen = async () => { try { screen.start() await wait(3000) } finally { screen.finish() } } const onLoadingPage = async () => { try { page.start() await wait(3000) } finally { page.finish() } } const onLoadingBackground = async () => { try { background.start() await wait(3000) } finally { background.finish() } } return ( ) ``` ## Usage ```tsx import { useLoading } from "@yamada-ui/react" ``` ```tsx import { useLoading } from "@/components/ui" ``` ```tsx import { useLoading } from "@workspaces/ui" ``` ```tsx const { screen, page, background } = useLoading() ``` `useLoading` returns instances of `screen`, `page`, and `background`. Each instance provides several methods: - `start`: Starts the loading animation. - `update`: Updates the loading animation. - `finish`: Finishes the loading animation. - `force`: Forces the loading animation to update. ### Change Loading Scheme ```tsx const { screen, page, background } = useLoading() return ( ) ``` ### Set Duration To set the duration, set a number (milliseconds) to `duration`. ```tsx const { screen, page, background } = useLoading() return ( ) ``` ### Set Message To set a message, set a `ReactNode` to `message`. ```tsx const { screen, page, background } = useLoading() return ( ) ``` ### Update Message To update a message, use `update`. ```tsx const { screen, page, background } = useLoading() const onLoadingScreen = async () => { try { screen.start({ message: "Loading" }) await wait(3000) screen.update({ message: "Please Wait" }) await wait(3000) } finally { screen.finish() } } const onLoadingPage = async () => { try { page.start({ message: "Loading" }) await wait(3000) page.update({ message: "Please Wait" }) await wait(3000) } finally { page.finish() } } const onLoadingBackground = async () => { try { background.start({ message: "Loading" }) await wait(3000) background.update({ message: "Please Wait" }) await wait(3000) } finally { background.finish() } } return ( ) ``` ## Configuration ### Change Loading Scheme ```tsx const config = extendConfig({ loading: { background: { loadingScheme: "puff" }, page: { loadingScheme: "dots" }, screen: { loadingScheme: "grid" }, }, }) const App: FC = () => { const { screen, page, background } = useLoading() return ( ) } return ( ) ``` # useLocalStorage ```tsx const [value, setValue, resetValue] = useLocalStorage({ key: "value", defaultValue: 1, }) return ( ) ``` ## Usage ```tsx import { useLocalStorage } from "@yamada-ui/react" ``` ```tsx import { useLocalStorage } from "@/components/ui" ``` ```tsx import { useLocalStorage } from "@workspaces/ui" ``` ```tsx const [value, setValue, resetValue] = useLocalStorage({ key: "value", defaultValue: 1, }) ``` # useMediaQuery ```tsx const large = useMediaQuery("(min-width: 1280px)") return {large ? "larger than 1280px" : "smaller than 1280px"} ``` ## Usage ```tsx import { useMediaQuery } from "@yamada-ui/react" ``` ```tsx import { useMediaQuery } from "@/components/ui" ``` ```tsx import { useMediaQuery } from "@workspaces/ui" ``` ```tsx const large = useMediaQuery("(min-width: 1280px)") ``` # useNotice ```tsx const notice = useNotice() return ( ) ``` ## Usage ```tsx import { useNotice } from "@yamada-ui/react" ``` ```tsx import { useNotice } from "@/components/ui" ``` ```tsx import { useNotice } from "@workspaces/ui" ``` ```tsx const notice = useNotice() ``` ### Change Variant ```tsx const notice = useNotice() return ( {(variant) => ( )} ) ``` ### Change Color Scheme ```tsx const notice = useNotice() return ( {(colorScheme) => ( )} ) ``` ### Change Loading Scheme ```tsx const notice = useNotice() return ( {(loadingScheme) => ( )} ) ``` ### Change Status To change the status, set the `status` to `"info"` or `"success"` etc. ```tsx const notice = useNotice() return ( {(status) => ( )} ) ``` ### Change Limit To change the limit, set the `limit` to a number. ```tsx const notice = useNotice({ limit: 10 }) return ( ) ``` ### Change Duration To change the duration, set the `duration` to a number. ```tsx const notice = useNotice({ duration: 10000 }) return ( ) ``` ### Keep Stay To keep the notice staying, set the `duration` to `null`. ```tsx const notice = useNotice({ duration: null }) return ( ) ``` ### Change Placement To change the placement, set the `placement` to `"start"` or `"end"` etc. ```tsx const notice = useNotice({ duration: null }) return ( {(placement) => ( )} ) ``` ### Change Close Strategy To change the close strategy, set the `closeStrategy` to `"click"` or `"drag"` etc. ```tsx const notice = useNotice() return ( {(closeStrategy) => ( )} {(closeStrategy) => ( )} ) ``` ### Close Notice To close the notice, use `close` or `closeAll`. ```tsx const notice = useNotice() const id = useRef(null) const onOpen = () => { id.current = notice({ closable: true, description: "お前が好きだ。", duration: 30000, title: "クラン・クラン", }) } const onClose = () => { if (id.current) notice.close(id.current) } const onCloseAll = () => { notice.closeAll() } return ( ) ``` ### Update Notice To update the notice, use `update`. ```tsx const notice = useNotice() const id = useRef(null) const onOpen = () => { id.current = notice({ colorScheme: "orange", description: "チャンスは目の前にあるものよ。", duration: 5000, title: "シェリル・ノーム", }) } const onUpdate = () => { if (id.current) notice.update(id.current, { colorScheme: "blue", description: "人生はワン・ツー・デカルチャー!!頑張れ、私。", duration: 5000, title: "ランカ・リー", }) } return ( ) ``` ## Configuration ### Make Notice Always Expand To make the notice always expand, set the `expand` to `true`. ```tsx import { UIProvider, extendConfig } from "@yamada-ui/react" const config = extendConfig({ notice: { expand: true, }, }) const App = () => { return ( ) } ``` ### Change Placement To change the placement, set the `placement` to `"start"` or `"end"` etc. ```tsx import { UIProvider, extendConfig } from "@yamada-ui/react" const config = extendConfig({ notice: { placement: "end-end",, }, }) const App = () => { return ( ) } ``` ### Change Limit To change the limit, set the `limit` to a number. ```tsx import { UIProvider, extendConfig } from "@yamada-ui/react" const config = extendConfig({ notice: { limit: 5, }, }) const App = () => { return ( ) } ``` ### Change Close Strategy To change the close strategy, set the `closeStrategy` to `"click"` or `"drag"` etc. ```tsx import { UIProvider, extendConfig } from "@yamada-ui/react" const config = extendConfig({ notice: { closeStrategy: "click", }, }) const App = () => { return ( ) } ``` # useOS ```tsx const os = useOS() return Your os is "{os}" ``` ## Usage ```tsx import { useOS } from "@yamada-ui/react" ``` ```tsx import { useOS } from "@/components/ui" ``` ```tsx import { useOS } from "@workspaces/ui" ``` ```tsx const os = useOS() ``` # useOutsideClick ```tsx const ref = useRef(null) const { open, onOpen, onClose } = useDisclosure() useOutsideClick({ ref, handler: onClose, }) return ( <> {open ? (
Hey, Click anywhere outside of me to close.
) : ( )} ) ``` ## Usage ```tsx import { useOutsideClick } from "@yamada-ui/react" ``` ```tsx import { useOutsideClick } from "@/components/ui" ``` ```tsx import { useOutsideClick } from "@workspaces/ui" ``` ```tsx const { open, onOpen, onClose } = useDisclosure() useOutsideClick({ ref, handler: onClose, }) ``` # usePrevious ```tsx const [flg, { toggle }] = useBoolean() const prevFlg = usePrevious(flg) return ( state: {String(flg)}, prev: {String(prevFlg)} ) ``` ## Usage ```tsx import { usePrevious } from "@yamada-ui/react" ``` ```tsx import { usePrevious } from "@/components/ui" ``` ```tsx import { usePrevious } from "@workspaces/ui" ``` ```tsx const [flg, { toggle }] = useBoolean() const prevFlg = usePrevious(flg) ``` # useProcessing ```tsx const { loading, start, finish } = useProcessing() const onClick = () => { start() setTimeout(() => finish(), 3000) } return ( ) ``` ## Usage ```tsx import { useProcessing } from "@yamada-ui/react" ``` ```tsx import { useProcessing } from "@/components/ui" ``` ```tsx import { useProcessing } from "@workspaces/ui" ``` ```tsx const { loading, start, finish } = useProcessing() ``` # usePromiseDisclosure ```tsx const { open, onClose, onOpen, onSuccess } = usePromiseDisclosure() const onClick = async () => { try { await onOpen() console.log("やるじゃねえか、サタン!!!") console.log("おめえはホントに世界の…") console.log("救世主かもな!!!!") } catch { console.error("地球は滅亡しました") } } return ( だ…大地よ海よ そして生きているすべての みんな… このオラにほんのちょっとずつだけ元気をわけてくれ…!!! き、きさまらいいかげんにしろーーーっ!!! さっさと協力しないかーーーっ!!! このミスター・サタンさまのたのみも、きけんというのかーーーっ!!! } cancel="わけない" open={open} success="わける" title="ミスター・サタン" onCancel={onClose} onClose={onClose} onSuccess={onSuccess} /> ) ``` ## Usage ```tsx import { usePromiseDisclosure } from "@yamada-ui/react" ``` ```tsx import { usePromiseDisclosure } from "@/components/ui" ``` ```tsx import { usePromiseDisclosure } from "@workspaces/ui" ``` ```tsx const { open, onClose, onOpen, onSuccess } = usePromiseDisclosure() ``` # useResizeObserver ```tsx const [flg, { toggle }] = useBoolean() const [ref, rect] = useResizeObserver() return ( {JSON.stringify(rect)}
Click me
) ``` ## Usage ```tsx import { useResizeObserver } from "@yamada-ui/react" ``` ```tsx import { useResizeObserver } from "@/components/ui" ``` ```tsx import { useResizeObserver } from "@workspaces/ui" ``` ```tsx const [ref, rect] = useResizeObserver() ``` # useTheme ```tsx const { theme } = useTheme() return {JSON.stringify(theme)} ``` ## Usage ```tsx import { useTheme } from "@yamada-ui/react" ``` ```tsx import { useTheme } from "@/components/ui" ``` ```tsx import { useTheme } from "@workspaces/ui" ``` ```tsx const { themeScheme, changeThemeScheme } = useTheme() ``` :::note For more information about themes, please see [here](https://yamada-ui.com/docs/theming.md). ::: ### Switching Themes ```tsx const { themeScheme, changeThemeScheme } = useTheme() return ( The current scheme is "{themeScheme}" Primary Secondary Primary Secondary ) ``` :::warning In order to switch themes, you need to prepare multiple themes. For more details, please check [here](https://yamada-ui.com/docs/theming/switching-themes.md). ::: # useTimeout ```tsx const [state, setState] = useState(1) useTimeout(() => setState((prev) => prev + 1), 3000) return Current state: {state} ``` ## Usage ```tsx import { useTimeout } from "@yamada-ui/react" ``` ```tsx import { useTimeout } from "@/components/ui" ``` ```tsx import { useTimeout } from "@workspaces/ui" ``` ```tsx const [state, setState] = useState(1) useTimeout(() => setState((prev) => prev + 1), 3000) ``` # useUpdateBreakpointEffect ```tsx const [device, setDevice] = useState("unknown"); useUpdateBreakpointEffect(breakpoint => { if (breakpoint === "sm") { setDevice("mobile"); } else if (breakpoint === "md") { setDevice("tablet"); } else { setDevice("desktop"); } }, []); return The current device is "{device}"
; ``` ## Usage ```tsx import { useUpdateBreakpointEffect } from "@yamada-ui/react" ``` ```tsx import { useUpdateBreakpointEffect } from "@/components/ui" ``` ```tsx import { useUpdateBreakpointEffect } from "@workspaces/ui" ``` ```tsx const [device, setDevice] = useState("unknown") useUpdateBreakpointEffect((breakpoint) => { if (breakpoint === "sm") { setDevice("mobile") } else if (breakpoint === "md") { setDevice("tablet") } else { setDevice("desktop") } }, []) ``` # useUpdateEffect ```tsx const [state, setState] = useState(1) const [updateState, setUpdateState] = useState(1) const [flg, { toggle }] = useBoolean() useEffect(() => { setState((prev) => prev + 1) }, [flg]) useUpdateEffect(() => { setUpdateState((prev) => prev + 1) }, [flg]) return ( state changed by useEffect: {String(state)} state changed by useUpdateEffect: {String(updateState)} ) ``` ## Usage ```tsx import { useUpdateEffect } from "@yamada-ui/react" ``` ```tsx import { useUpdateEffect } from "@/components/ui" ``` ```tsx import { useUpdateEffect } from "@workspaces/ui" ``` ```tsx useUpdateEffect(() => {}, []) ``` # useValue ```tsx const breakpoint = useBreakpoint() const color = useValue({ base: "red", md: "green" }) return The current breakpoint is "{breakpoint}" ``` ```tsx const { colorMode } = useColorMode() const color = useValue(["green", "red"]) return The current colorMode is "{colorMode}" ``` ## Usage ```tsx import { useValue } from "@yamada-ui/react" ``` ```tsx import { useValue } from "@/components/ui" ``` ```tsx import { useValue } from "@workspaces/ui" ``` ```tsx const color = useValue({ base: "red", md: "green" }) ``` :::note `useValue` is using [useBreakpointValue](https://yamada-ui.com/hooks/use-breakpoint-value.md) and [useColorModeValue](https://yamada-ui.com/hooks/use-color-mode-value.md). ::: # useWindowEvent ```tsx const [count, setCount] = useState(0) useWindowEvent("click", () => { setCount((prev) => prev + 1) }) return Click count: {count} ``` ## Usage ```tsx import { useWindowEvent } from "@yamada-ui/react" ``` ```tsx import { useWindowEvent } from "@/components/ui" ``` ```tsx import { useWindowEvent } from "@workspaces/ui" ``` ```tsx const [count, setCount] = useState(0) useWindowEvent("click", () => { setCount((prev) => prev + 1) }) ```