Skip to content

Commit eb246ef

Browse files
perf: avoid calling executeOnUIRuntimeSync if shared value has initial value
1 parent 18b2030 commit eb246ef

File tree

1 file changed

+25
-6
lines changed

1 file changed

+25
-6
lines changed

packages/react-native-reanimated/src/mutables.ts

Lines changed: 25 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
import {
33
executeOnUIRuntimeSync,
44
makeShareableCloneRecursive,
5+
runOnJS,
56
runOnUI,
67
shareableMappingCache,
78
} from 'react-native-worklets';
@@ -94,10 +95,14 @@ function hideInternalValueProp<Value>(mutable: PartialMutable<Value>) {
9495
});
9596
}
9697

97-
export function makeMutableUI<Value>(initial: Value): Mutable<Value> {
98+
export function makeMutableUI<Value>(
99+
initial: Value,
100+
setIsDirty?: () => void
101+
): Mutable<Value> {
98102
'worklet';
99103
const listeners = new Map<number, Listener<Value>>();
100104
let value = initial;
105+
let isDirty = false;
101106

102107
const mutable: PartialMutable<Value> = {
103108
get value() {
@@ -114,6 +119,10 @@ export function makeMutableUI<Value>(initial: Value): Mutable<Value> {
114119
listeners.forEach((listener) => {
115120
listener(newValue);
116121
});
122+
if (setIsDirty && !isDirty && value !== initial) {
123+
isDirty = true;
124+
runOnJS(setIsDirty)();
125+
}
117126
},
118127
modify: (modifier, forceUpdate = true) => {
119128
valueSetter(
@@ -140,23 +149,33 @@ export function makeMutableUI<Value>(initial: Value): Mutable<Value> {
140149
}
141150

142151
function makeMutableNative<Value>(initial: Value): Mutable<Value> {
152+
let isDirty = false;
153+
const setIsDirty = () => {
154+
isDirty = true;
155+
};
156+
143157
const handle = makeShareableCloneRecursive({
144158
__init: () => {
145159
'worklet';
146-
return makeMutableUI(initial);
160+
return makeMutableUI(initial, setIsDirty);
147161
},
148162
});
149163

150164
const mutable: PartialMutable<Value> = {
151165
get value(): Value {
152166
checkInvalidReadDuringRender();
153-
const uiValueGetter = executeOnUIRuntimeSync((sv: Mutable<Value>) => {
154-
return sv.value;
155-
});
156-
return uiValueGetter(mutable as Mutable<Value>);
167+
if (isDirty) {
168+
const uiValueGetter = executeOnUIRuntimeSync((sv: Mutable<Value>) => {
169+
return sv.value;
170+
});
171+
return uiValueGetter(mutable as Mutable<Value>);
172+
} else {
173+
return initial;
174+
}
157175
},
158176
set value(newValue) {
159177
checkInvalidWriteDuringRender();
178+
isDirty = true;
160179
runOnUI(() => {
161180
mutable.value = newValue;
162181
})();

0 commit comments

Comments
 (0)