I have a hook that adds a header tag in order to load a script, but in case two components are using it, the hook could fall into the case that the header is added twice.
There are several ways to avoid this. Two of them could be:
const addHeaderTag = () => {...}. I could add a property to it and check if the function is called just once, otherwise return silently. It could be safe because the function is defined by me and I control the function object, plus javascript is monothread and concurrency is out of scope;Do you see other better ways? Do you see any problem to the solutions I had in mind?
A solution for this would be using a variable outside of your custom hook to check whether or not your hook is already called
import { useEffect } from "react";
let isCalled = false;
export const useOnce = () => {
useEffect(() => {
if (!isCalled) {
// do this only once, call your function here
console.log("hey there");
isCalled = true;
}
}, []);
return isCalled;
};
The reason this works is because when you import the same module multiple times, the code in that module is still only evaluated once.
That means isCalled in this case is only initialized once, so we can depend on it to check/set the value accordingly for the entire app.