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:
- Go to https://codesandbox.io/s/jovial-bouman-1d0yik?file=/components/counter.js
- Open codesandbox console
- Click on Increment button
- 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
Describe the bug
Using
useRefanduseMemotogether produces weird results.It's easier to explain with code:
The
console.loglogs null half of the times. I thinkref.currentshould never be null.To Reproduce
Steps to reproduce the behavior:
nulllogged half of the timeExpected behavior
ref.currentshouldn't be null. If I remove theuseMemoit works as expected.React works as expected: https://codesandbox.io/s/condescending-gagarin-o29rj6?file=/src/App.js