I want to run a callback when a component mounts, but not on each render. Using useEffect
and an empty dependency array created warnings. I read on a different thread which I now can't find that this can be achieved by creating a custom hook:
import {useRef} from "react";
const useInitialise = (callback) => {
//TODO this is running every render!
const runOnce = useRef(false);
if (!runOnce.current) {
callback();
runOnce.current = true;
}
}
export default useInitialise;
Usage:
useInitialise(() => {
//callback
});
This is instead of using:
useEffect(() => {
//callback
}, []);
As this generates warnings. I understand that the hook will be called on each render, but why is the runOnce.current
not preventing the callback being run twice?