Skip to content

Commit

Permalink
Replace useRef with useState for useSharedValue (#5458)
Browse files Browse the repository at this point in the history
## Summary
The general idea here is that we can avoid the `makeMutable` call on
every single render. This change is also compatible with hot reloading.

We (at Discord) have been running this patch on top of our own
reanimated now for a few weeks and haven't noticed any side effects of
the change.

There has been a bit of additional discussion I've seen surrounding this
issue here:
#3199

## Test plan
N/A
  • Loading branch information
amadeus authored and Aleksandra Cynk committed Dec 12, 2023
1 parent 4649f71 commit d1daac4
Showing 1 changed file with 5 additions and 13 deletions.
18 changes: 5 additions & 13 deletions src/reanimated2/hook/useSharedValue.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
'use strict';
import { useEffect, useRef } from 'react';
import { useEffect, useState } from 'react';
import { cancelAnimation } from '../animation';
import type { SharedValue } from '../commonTypes';
import { makeMutable } from '../core';
Expand All @@ -15,19 +15,11 @@ export function useSharedValue<Value>(
initialValue: Value,
oneWayReadsOnly = false
): SharedValue<Value> {
const ref = useRef<SharedValue<Value>>(
makeMutable(initialValue, oneWayReadsOnly)
);

if (ref.current === null) {
ref.current = makeMutable(initialValue, oneWayReadsOnly);
}

const [mutable] = useState(() => makeMutable(initialValue, oneWayReadsOnly));
useEffect(() => {
return () => {
cancelAnimation(ref.current);
cancelAnimation(mutable);
};
}, []);

return ref.current;
}, [mutable]);
return mutable;
}

0 comments on commit d1daac4

Please sign in to comment.