UNPKG

@lobehub/ui

Version:

Lobe UI is an open-source UI component library for building AIGC web apps

1 lines 1.55 kB
{"version":3,"file":"useStableValue.mjs","names":[],"sources":["../../src/hooks/useStableValue.ts"],"sourcesContent":["import { useRef } from 'react';\n\nimport { isDeepEqual } from '@/utils/isDeepEqual';\n\n/**\n * Return the previous reference when the incoming value is structurally\n * identical to it, so callers don't have to wrap every prop-shaped object\n * in `useMemo` to keep downstream React reference checks happy.\n *\n * Motivation: when a structural prop like `componentProps={{ html: {\n * theme: 'dark' } }}` is passed inline, React's normal ref equality\n * forces every consumer downstream to re-run effects, recompute memos,\n * and — most importantly — remount any children whose deps include\n * sub-properties of that object (`components` for react-markdown is the\n * classic case). For Markdown rendering a streaming HTML preview that\n * blew the iframe up 50× per second.\n *\n * Comparison is structural for plain objects and arrays. Functions and\n * class instances are compared by reference — callers passing inline\n * callbacks still need `useCallback` to keep those stable. Don't use this\n * for state values you intend to compare with `===`.\n */\nexport const useStableValue = <T>(value: T): T => {\n const prevRef = useRef<T>(value);\n if (!isDeepEqual(prevRef.current, value)) {\n prevRef.current = value;\n }\n return prevRef.current;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAsBA,MAAa,kBAAqB,UAAgB;CAChD,MAAM,UAAU,OAAU,MAAM;AAChC,KAAI,CAAC,YAAY,QAAQ,SAAS,MAAM,CACtC,SAAQ,UAAU;AAEpB,QAAO,QAAQ"}