Search code examples
reactjsreact-nativereact-native-reanimatedreact-native-reanimated-v2

How do i trigger a useEffect based on a sharedValue from the Reanimated libary


How do i trigger a useEffect based on a sharedValue from the Reanimated libary?

 const sharedValue = useSharedValue(0);
  useEffect(() => {
    console.log("exectue functions");
  }, [sharedValue.value]);

Is there a best practice for this. Or is there another way to trigger functions (sync and async) based on a change in a sharedValue.


Solution

  • You can use:

    1. useAnimatedReaction;
    2. useDerivedValue;

    Solution with useAnimatedReaction

    const sharedValue = useSharedValue(0);
    
    useAnimatedReaction(() => {
        return sharedValue.value;
      }, (result, previous) => {
        if (result !== previous) {
           console.log(result)
        }
     }, []); // No need to pass dependencies
    

    Solution with useDerivedValue

    const sharedValue = useSharedValue(0);
    
    useDerivedValue(() => {
        console.log(sharedValue.value);
    }, []); // No need to pass dependencies