useDataState
unlumen-ui/hooks-use-data-stateFreeHook
A hook that allows you to get the data-state of an element.
Install it
npx shadcn@latest add https://ui.unlumen.com/r/hooks-use-data-state.jsonSource
1"use client";23import * as React from "react";45type DataStateValue = string | boolean | null;67function parseDatasetValue(value: string | null): DataStateValue {8 if (value === null) return null;9 if (value === "" || value === "true") return true;10 if (value === "false") return false;11 return value;12}1314function useDataState<T extends HTMLElement = HTMLElement>(15 key: string,16 forwardedRef?: React.Ref<T | null>,17 onChange?: (value: DataStateValue) => void,18): [DataStateValue, React.RefObject<T | null>] {19 const localRef = React.useRef<T | null>(null);20 React.useImperativeHandle(forwardedRef, () => localRef.current as T);2122 const getSnapshot = (): DataStateValue => {23 const el = localRef.current;24 return el ? parseDatasetValue(el.getAttribute(`data-${key}`)) : null;25 };2627 const subscribe = (callback: () => void) => {28 const el = localRef.current;29 if (!el) return () => {};30 const observer = new MutationObserver((records) => {31 for (const record of records) {32 if (record.attributeName === `data-${key}`) {33 callback();34 break;35 }36 }37 });38 observer.observe(el, {39 attributes: true,40 attributeFilter: [`data-${key}`],41 });42 return () => observer.disconnect();43 };4445 const value = React.useSyncExternalStore(subscribe, getSnapshot);4647 React.useEffect(() => {48 if (onChange) onChange(value);49 }, [value, onChange]);5051 return [value, localRef];52}5354export { useDataState, type DataStateValue };
Files it writes
More from Unlumen Ui
All 233 items| Component | Registry | Kind | Access | Installs | Command |
|---|---|---|---|---|---|
| useAutoHeighthooks-use-auto-height | Unlumen Ui | Hooks | Free | no deps | |
| Use Controlled Statehooks-use-controlled-state | Unlumen Ui | Hooks | Free | no deps | |
| useIsInViewhooks-use-is-in-view | Unlumen Ui | Hooks | Free | 1 dep | |
| useMotionValueStatehooks-use-motion-value-state | Unlumen Ui | Hooks | Free | 1 dep |
