useCallbackRefis a hook provided byuse-callback-refpackage
Why does useEffect triggered twice when having in the dependency array the .current of the useCallbackRef result?
import { useCallback, useEffect, useRef, useState } from "react";
import { useCallbackRef } from "use-callback-ref";
function App() {
const [useCbRefCounter, setUseCbRefCounter] = useState(0);
const [useCbRefEffectCounter, setUseCbRefEffectCounter] = useState(0);
const divCbRef = useCallbackRef(null, () =>
// This is called once
setUseCbRefCounter((counter) => counter + 1)
);
useEffect(() => {
if(!divCbRef.current) {
return;
}
// This is called twice
setUseCbRefEffectCounter((counter) => counter + 1);
}, [divCbRef.current]);
// ...
}
(The useEffect is not triggered with null as one might think)
Sandbox Demo with a comparison of the number of calls when the ref is changing