Skip to content

Instantly share code, notes, and snippets.

@kmagiera
Created June 12, 2020 08:00
Show Gist options
  • Save kmagiera/9f07591cbf4b7b5299122a0ecec46478 to your computer and use it in GitHub Desktop.
Save kmagiera/9f07591cbf4b7b5299122a0ecec46478 to your computer and use it in GitHub Desktop.
import React, { useEffect, useRef, useCallback, useState } from 'react';
import {
Text,
View,
YellowBox,
NativeModules,
Platform,
Button,
Animated,
} from 'react-native';
import { withTiming, runOnUI, makeShareable } from 'react-native-reanimated';
// 1
function someWorklet(greeting) {
'worklet';
console.log("Hey I'm running on the UI thread");
}
// 2
function someWorklet(greeting) {
'worklet';
console.log(greeting, 'From the UI thread');
}
function onPress() {
runOnUI(someWorklet)('Howdy');
}
// 3
const width = 135.5;
function otherWorklet() {
'worklet';
console.log('Captured width is', width);
}
// 4
function returningWorklet() {
'worklet';
return "I'm back";
}
function someWorklet() {
'worklet';
let what = returningWorklet();
console.log('On the UI thread, other worklet says', what);
}
// 5
function callback(text) {
console.log('Running on the RN thread', text);
}
function someWorklet() {
'worklet';
console.log("I'm on UI but can call methods from the RN thread");
callback('can pass arguments too');
}
// 6
const style = useAnimatedStyle(() => {
// when defining method in one of the hooks from reanimated, you don't
// need to add 'worklet' directive. It is a worklet by default.
return {
width: 64,
};
});
// 7
function fff() {
return (
<View style={styles.container}>
{/* you can mix static RN styles and animated styles */}
<Animated.View style={[styles.box, style]} />
</View>
);
}
// 8
function SomeComponent() {
const randomWidth = useSharedValue(64);
const style = useAnimatedStyle(() => {
return {
// get the value carried by `randomWidth` SV by accessing value field
width: randomWidth.value,
};
});
return (
<View style={styles.container}>
<Animated.View style={[styles.box, style]} />
</View>
);
}
// 9
function ggg() {
return (
<View style={styles.container}>
<Animated.View style={[styles.box, style]} />
<Button
title="Random width"
onPress={() => {
randomWidth.value = Math.random() * 150 + 50;
}}
/>
</View>
);
}
// 10
const style = useAnimatedStyle(() => {
if (enabled) {
return {
opacity: 1,
...otherStyles,
};
} else {
return {
opacity: 0,
...someDisabledStyles,
};
}
});
// 11
import { withSpring } from 'react-native-reanimated';
const style = useAnimatedStyle(() => {
return {
width: withSpring(randomWidth.value),
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment