Search code examples
react-nativeanimationreact-native-reanimatedreact-native-reanimated-v2

How to update shared value after async operation?


const [action, setAction] = useState(true);
const sharedVal = useSharedValue(action ? 10 : 20)
useEffect(() => {
    setTimeout(() => {
        setAction(false)
    }, 2000)
}, [])

In the above code, the value of shareVal doesn't change the value of action changes. What is the best way to update value of sharedVal after the timeout.


Solution

  • you'll have to run a side effect when action changes.

    useEffect(() => {
      
      sharedVal.value = action ? 10 : 20;
    
      // this will run when action is updated 
    }, [action]);
    

    or you can just do sharedVal.value = someValue wherever you want.

    documentation

    (...) The reference is an object with .value property, that can be accessed and modified from worklets, but also updated directly from the main JS thread.