How can I pass a useSharedValue to another component so it can be used in useAnimatedStyle, but only allow read access (preventing .value from being mutated)? #8246
-
Hello everyone, |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Hey @Choco-milk-for-u! 1. TypeScript solutionIf you use TypeScript, then you can use the type that won't allow function ComponentA() {
const sv = useSharedValue(0);
return <ComponentB sv={sv} />;
}
type ComponentBProps = {
sv: Readonly<SharedValue<number>>;
};
function ComponentB({ sv }: ComponentBProps) {
useEffect(() => {
// Writing is not allowed
sv.value = 1;
// Reading is fine
console.log('sv', sv.value);
}, [sv]);
return null;
} ![]() It still won't prevent you from assigning the value if you decide to ignore the TS error. For more safety, you can use the following approach. 2. Using Derived ValuesInstead of passing a function ComponentA() {
const sv = useSharedValue(0);
const svDerived = useDerivedValue(() => {
return sv.value + 1;
});
return <ComponentB sv={svDerived} />;
}
type ComponentBProps = {
sv: DerivedValue<number>;
};
function ComponentB({ sv }: ComponentBProps) {
useEffect(() => {
console.log('ComponentB');
// Writing is not allowed
sv.value = 100;
setTimeout(() => {
console.log('sv timeout', sv.value);
}, 1000);
// Reading is fine
console.log('sv', sv.value);
}, [sv]);
return null;
} The use of the See that in the example above it still returns the same value after the timeout. When you replace the |
Beta Was this translation helpful? Give feedback.
Hey @Choco-milk-for-u!
1. TypeScript solution
If you use TypeScript, then you can use the type that won't allow
.value
assignment like this:It still won't prevent you from assigning the value if you decide to ignore the TS error. For more safety, you can use the following approach.
2. Using Derived Values
Instead of passing a
Shared…