Skip to content

refs in memoized elements #3695

@pomber

Description

@pomber

Describe the bug

Using useRef and useMemo together produces weird results.

It's easier to explain with code:

function Counter() {
  const [count, setCount] = useState(0);
  const inc = () => setCount(count + 1);

  const ref = useRef(null);
  const element = useMemo(() => <div ref={ref}>hey</div>, []);

  useEffect(() => {
    console.log(ref.current);
  }, [count]);

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={inc}>Increment</button>
      <div key={count}>{element}</div>
    </div>
  );
}

The console.log logs null half of the times. I think ref.current should never be null.

To Reproduce

Steps to reproduce the behavior:

  1. Go to https://codesandbox.io/s/jovial-bouman-1d0yik?file=/components/counter.js
  2. Open codesandbox console
  3. Click on Increment button
  4. See null logged half of the time

Expected behavior

ref.current shouldn't be null. If I remove the useMemo it works as expected.

React works as expected: https://codesandbox.io/s/condescending-gagarin-o29rj6?file=/src/App.js

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions