I am building a next.js website and intend to include Google AdSense at some point in the future. After following some examples and implementing the scripts as per a Next project I am hitting a wall with this error:
"adsbygoogle.push() error: All ins elements in the DOM with class=adsbygoogle already have ads in them."
My component looks like this:
const GoogleAdSenseContainer = ({
client = AdSense_ID,
slot,
className,
responsive = true,
displayAdSize = displayAdSizes.responsive,
adUnitKey,
}: Props) => {
const router = useRouter();
const loadAds = () => {
try {
window.adsbygoogle = window.adsbygoogle || [];
window.adsbygoogle.push({});
} catch (error) {
console.error('🚨 AdSense Error', error);
}
};
useEffect(() => {
loadAds();
}, [adUnitKey, router]);
return (
<div
className={cx(styles.adSenseContainer, className)}
style={{ overflow: 'hidden' }}
key={adUnitKey}
>
<span className={styles.adLabel}>Advertisement</span>
<ins
className='adsbygoogle'
style={displayAdSize}
data-ad-client={client}
data-ad-slot={slot}
data-ad-format={responsive && 'auto'}
data-full-width-responsive={responsive}
></ins>
</div>
);
};
This pretty much works as intended, however, because of the new remounting behaviour in React 18:
With Strict Mode starting in React 18, whenever a component mounts in development, React will simulate immediately unmounting and remounting the component.
I am getting the error highlighted above.
I am not entirely sure how to avoid this error, I have attempted to cleanup the hook. I have also tried checking if ads already exist (but this doesn't seem to want to work).
Any help would be much appreciated!