react icon indicating copy to clipboard operation
react copied to clipboard

Bug: Inefficiency when hooks return multiple values

Open mohebifar opened this issue 1 month ago • 0 comments

React compiler inefficiently re-evaluates code when dependencies that do not affect the result have changed. Specifically, when the hook returns multiple values.

Input code:

export default function Test() {
  const [data, refetch] = useData();

  const y = deepClone(data);

  return (
    <div>
      <button onClick={refetch}>
        Refetch
      </button>
      <span>
        {JSON.stringify(y)}
      </span>
    </div>
  );
}

Check the output JS here - Link to Playground

Steps To Reproduce

  1. Use the provided original code in a React component.
  2. Observe the generated code by the React compiler.
  3. Note that deepClone(data) is re-evaluated when refetch changes.

Check the playground link above ^

The current behavior

  • The line const y = deepClone(data); is re-evaluated whenever refetch changes, even if data remains the same.
  • This inefficiency arises because the compiler does not memoize y independently from other variables like t1.

The expected behavior

y should be memoized separately to avoid re-computation when only refetch changes and data remains the same.

mohebifar avatar May 17 '24 00:05 mohebifar