Adding to Fabian Schultz
This happens because in the first case, you're passing a reference of the function to the ref
. During the initial render, the referenced function will be instantiate
(a instance is created) and the element
will be passed to that function. For the following renders(re-renders), this instance remains the same. So, React won't call this function as it is already being called.
But, in the second case, a arrow function is passed in as a value. So, for every re-renders the function will be passed again as the value. This results in two instances of arrow functions. One, from the previous render and the second from the recent render. Due to this, React nullifies
the previous instance of the function. So, it returns null
for the previous instance of the function and returns the element
to the recent instance of the function.
Point to take: Always use function reference for ref
Hope this helps!
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…