Skip to content

Commit

Permalink
Merge pull request #607 from callstack-internal/feat/useonyx-metrics
Browse files Browse the repository at this point in the history
feat: decorate useOnyx.getSnapshot with performance metrics
  • Loading branch information
mountiny authored Dec 10, 2024
2 parents c25f9a0 + 8205201 commit f97eb24
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 9 deletions.
7 changes: 0 additions & 7 deletions lib/metrics.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
import PerformanceProxy from './dependencies/PerformanceProxy';

const decoratedAliases = new Set();

/**
* Capture a measurement between the start mark and now
*/
Expand All @@ -21,11 +19,6 @@ function isPromiseLike(value: unknown): value is Promise<unknown> {
* Wraps a function with metrics capturing logic
*/
function decorateWithMetrics<Args extends unknown[], ReturnType>(func: (...args: Args) => ReturnType, alias = func.name) {
if (decoratedAliases.has(alias)) {
throw new Error(`"${alias}" is already decorated`);
}

decoratedAliases.add(alias);
function decorated(...args: Args) {
const mark = PerformanceProxy.mark(alias, {detail: {args, alias}});

Expand Down
14 changes: 12 additions & 2 deletions lib/useOnyx.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
import {deepEqual, shallowEqual} from 'fast-equals';
import {useCallback, useEffect, useRef, useSyncExternalStore} from 'react';
import {useCallback, useEffect, useMemo, useRef, useSyncExternalStore} from 'react';
import type {DependencyList} from 'react';
import OnyxCache, {TASK} from './OnyxCache';
import type {Connection} from './OnyxConnectionManager';
import connectionManager from './OnyxConnectionManager';
import OnyxUtils from './OnyxUtils';
import * as GlobalSettings from './GlobalSettings';
import type {CollectionKeyBase, KeyValueMapping, OnyxCollection, OnyxKey, OnyxValue} from './types';
import useLiveRef from './useLiveRef';
import usePrevious from './usePrevious';
import decorateWithMetrics from './metrics';

type BaseUseOnyxOptions = {
/**
Expand Down Expand Up @@ -321,11 +323,19 @@ function useOnyx<TKey extends OnyxKey, TReturnValue = OnyxValue<TKey>>(
[key, options?.initWithStoredValues, options?.reuseConnection, checkEvictableKey],
);

const getSnapshotDecorated = useMemo(() => {
if (!GlobalSettings.isPerformanceMetricsEnabled()) {
return getSnapshot;
}

return decorateWithMetrics(getSnapshot, 'useOnyx.getSnapshot');
}, [getSnapshot]);

useEffect(() => {
checkEvictableKey();
}, [checkEvictableKey]);

const result = useSyncExternalStore<UseOnyxResult<TReturnValue>>(subscribe, getSnapshot);
const result = useSyncExternalStore<UseOnyxResult<TReturnValue>>(subscribe, getSnapshotDecorated);

return result;
}
Expand Down

0 comments on commit f97eb24

Please sign in to comment.