facebook / react

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

[Compiler Bug]: Mutating a ref returned from a function warns #29196

Open atomiks opened 2 months ago

atomiks commented 2 months ago

What kind of issue is this?

Link to repro

https://playground.react.dev/#N4Igzg9grgTgxgUxALhAMygOzgFwJYSYAEUYCAsgJ4BKCaAFAJRHAA6xRMCOsxpCtBowDc7AL7t2GbPkJEAEggA2SiExbsiROITA5OdIgF4SZKoKaiO-AKJo0CXPXVGAfBo5auaAHRxYXJj6JgDkOAh6IVZaYiLiIGJAA

Repro steps

When consuming mutable refs from custom hooks (or via props), the consuming components should be allowed to mutate them inside effects/event handlers.

function useMyRef() {
  return useRef('test');
}

function Hello() {
  const ref = useMyRef();
  useEffect(() => {
    ref.current = 'next';
//  ~~~ InvalidReact: Mutating a value returned from a function whose return value should not be mutated. Found mutation of `ref` (8:8)
  });
}

How often does this bug happen?

Every time

What version of React are you using?

19

josephsavona commented 2 months ago

Thanks for posting! The cause is very similar to https://github.com/facebook/react/issues/29160#issuecomment-2118621984 — the compiler currently assumes that only values that come directly from useRef() are refs. As with #29160 , we will likely need to explore a heuristic for understanding which values may be refs, based on the ecosystem convention of "ref" or "-Ref".

gsathya commented 2 months ago

we will likely need to explore a heuristic for understanding which values may be refs, based on the ecosystem convention of "ref" or "-Ref".

I'm looking into adding this. Assigning this to myself