|
1 | 1 | import { useEffect, useRef, useMemo, type EffectCallback, type DependencyList } from "react" |
2 | 2 | import { deepCompare } from "../utils/compare" |
3 | 3 |
|
| 4 | +/** |
| 5 | + * Similar to useEffect but performs deep comparison of dependencies instead of shallow comparison. |
| 6 | + * Useful when dependencies are objects or arrays that may be recreated on each render. |
| 7 | + * |
| 8 | + * @example |
| 9 | + * ```tsx |
| 10 | + * import { useDeepCompareEffect } from '@nosto/nosto-react' |
| 11 | + * |
| 12 | + * function MyComponent({ user }: { user: { id: string, preferences: string[] } }) { |
| 13 | + * useDeepCompareEffect(() => { |
| 14 | + * console.log('User preferences changed:', user.preferences) |
| 15 | + * // This will only run when user object actually changes, |
| 16 | + * // not when it's recreated with same values |
| 17 | + * }, [user]) |
| 18 | + * |
| 19 | + * return <div>User: {user.id}</div> |
| 20 | + * } |
| 21 | + * ``` |
| 22 | + * |
| 23 | + * @example Comparing arrays and objects |
| 24 | + * ```tsx |
| 25 | + * import { useDeepCompareEffect } from '@nosto/nosto-react' |
| 26 | + * |
| 27 | + * function ProductList({ filters, sortOptions }: { |
| 28 | + * filters: { category: string, price: { min: number, max: number } } |
| 29 | + * sortOptions: string[] |
| 30 | + * }) { |
| 31 | + * useDeepCompareEffect(() => { |
| 32 | + * // This effect will only run when filters or sortOptions actually change |
| 33 | + * fetchProducts(filters, sortOptions) |
| 34 | + * }, [filters, sortOptions]) |
| 35 | + * |
| 36 | + * return <div>Product list</div> |
| 37 | + * } |
| 38 | + * ``` |
| 39 | + * |
| 40 | + * @param callback The effect callback function |
| 41 | + * @param dependencies Array of dependencies to deep compare |
| 42 | + * |
| 43 | + * @group Utilities |
| 44 | + */ |
4 | 45 | export function useDeepCompareEffect(callback: EffectCallback, dependencies: DependencyList) { |
5 | 46 | return useEffect(callback, useDeepCompareMemoize(dependencies)) |
6 | 47 | } |
|
0 commit comments