Search code examples
reactjsconstructorscopecdn

How do you use Library Constructer outside of a useEffect hook?


I am using a library in my React app (they do not have a node package) that I am bringing in on a CDN in the <head>.

I am using the useEffect hook to prevent it from calling the library constructor over and over, which just breaks it. But I cannot get the library to show itself outside of the hook.

example...

export default function ReactComponent(){
   let tdna = undefined;

   useEffect(() => {
        tdna = new TypingDNA();
        console.log(tdna)
    }, [])
    
    console.log(tdna)
}

The first console log shows the library, and only once as I expected. But my attempt to define it on the globalscope has been futile. 😂


Solution

  • I was able to find a solution with the useRef hook to get a stable value that does not change during subsequent renders

    export default function ReactComponent(){
       let tdna = useRef();
    
       useEffect(() => {
           if (!tdna.current) {
                tdna.current = new TypingDNA();
            }
        }, [tdna])
        
        console.log(tdna.current)
    }