facebook / react

The library for web and native user interfaces.
https://react.dev
MIT License
224.78k stars 45.84k forks source link

[Compiler Bug]: react native reanimated shared value mutation #29640

Open AlirezaHadjar opened 1 month ago

AlirezaHadjar commented 1 month ago

What kind of issue is this?

Link to repro

https://github.com/AlirezaHadjar/react-compiler-shared-value-bug

Repro steps

Hi, I'm using polyfill in react native to get the compiler working and noticing that the compiler is complaining about reanimated shared value mutations which is a very common pattern in react native.

  const onPress = () => {
    translateX.value = withTiming((Math.random() - 0.5) * 100);
  };

Screenshot 2024-05-29 at 12 40 14 PM

And the health-check command also confirms that App.tsx is not compiled.

Screenshot 2024-05-29 at 12 42 33 PM

Steps to build the project:

  1. yarn install
  2. yarn ios

@josephsavona this is the issue that we discussed on Twitter

How often does this bug happen?

Every time

What version of React are you using?

18.2

josephsavona commented 1 month ago

Thanks for posting. We've discussed this previously with the Reanimated team.

React requires that values returned from hooks are immutable. This is because React's reactivity model is fundamentally based on immutability, both for developer reasoning and to enable features such as concurrent rendering, where React may render multiple distinct versions of your UI with different base states.

The one exception to this rule is the ref type (created with createRef() or useRef()). They are the escape hatch for when you need a value that can be directly mutated, rather than copying (spreading) and changing the new version as we do with state values. The reason that refs can be "safely" mutated is that they can't be accessed during render, which helps developers avoid accidentally rendering stale results.

Our recommendation for APIs such as Reanimated's SharedValue API:

gkueny commented 1 month ago

Thank’s @josephsavona for the explanation.

If I understand correctly, as react-native developer we have to wait some api design update by react-native-reanimated team to be able to use react-compiler with our component that use x.value = y; syntax ?

josephsavona commented 1 month ago

An alternative would be to use your own helper for assigning the value. Instead of x.value = y, create your own updateSharedValue(sharedValue, value) helper function and call it.

AlirezaHadjar commented 1 month ago

Thank you for the insight 🙌

gsathya commented 3 weeks ago

The compiler should actually compile this fine, I think the healthcheck script doesn't track the reanimated import and turn on the correct type information. This should just be a fix in the health check script.