I have some React Components that are going to be used a lot all over my App.
I'd like that only the first time they get printed in the DOM, they return as
<symbol id="SVGComponent"><SVGComponent></symbol><use href="#SVGComponent" />
while every other following printing should be only
<use href="#SVGComponent" />
since the symbol has already been declared in the page
const [firstTime, setFirstTime] = useState(true);
useEffect(() => { setFirstTime(false) }, []);
if (firstTime) {
return (<symbol id="Component"><Path /></symbol>);
}
else {
return(<use href="#Component"/>);
}
This is my code so far but the condition always return false
.
How is that possibile in React with useEffect
?
Thanks in advance for your help
So I ended up replying to myself again for anyone coming. Fortunately what I want to achieve is possibile with just a few lines of code. Thanks this guy for the code: https://stackoverflow.com/a/57331421/3937587
let instancesCount = 0
function Component(props) {
const [firstRender, setFirstRender] = useState(false)
useEffect(() => {
setFirstRender(instancesCount === 0)
instancesCount++
return () => { instancesCount-- }
}, [])
if (firstRender)
//do something only the first time the component appears
}