title: How to create a Functional React Component using Cytoscape.js?
body: <p>I am working with Cytoscape.js and React. I have a functional GraphComponent that receives the list of elements used to render the Cytoscape graph, and a list of nodes I wish to animate.</p>
  <p>The problem I have is that I cannot figure out how to persist the 'cy' object so that I may access it at a later time. Specifically, I would like to add a class to the nodes in path.</p>
  <pre><code>const MyComponent = ({ myElements, path }) =&gt; {
      
      useEffect(() =&gt; {
  
          const cy = {
              ...
              elements: myElements
              ...
          }
  
      }, []);
  
      
      useEffect(() =&gt; {
  
          // This fails since 'cy' is undefined
          cy.$id(&quot;A&quot;).addClass(&quot;highlighted&quot;);
  
      }, [path]);
  
      return (
          &lt;div id=&quot;cy&quot; /&gt;
      );
  }
  </code></pre>
  <p>Idea #1: Create a variable 'cy' that I can then set the value to in useEffect.</p>
  <p>Problem: After the initial render the value of 'cy' is lost</p>
  <pre><code>const MyComponent = ({ myElements, path }) =&gt; {
  
      let cy;
      
      useEffect(() =&gt; {
  
          cy = {
              ...
              elements: myElements
              ...
          }
  
      }, []);
  
      useEffect(() =&gt; {
  
          // This fails since 'cy' is undefined
          cy.$id(&quot;A&quot;).addClass(&quot;highlighted&quot;);
  
      }, [path]);
  
      return (
          &lt;div id=&quot;cy&quot; /&gt;
      );
  }
  </code></pre>
  <p>Idea #2: Save cy as state.</p>
  <p>Problem: Cy is not properly initialized</p>
  <pre><code>const MyComponent = ({ myElements, path }) =&gt; {
  
      const [cy, setCy] = useState({});
      
      useEffect(() =&gt; {
  
          setCy({
              ...
              elements: myProp
              ...
          });
  
      }, []);
  
      useEffect(() =&gt; {
  
          cy.$id(&quot;A&quot;).addClass(&quot;highlighted&quot;);
  
      }, [path]);
  
      return (
  
          // This fails since cy is not initialized to a cytoscape object when component mounts
          &lt;div id=&quot;cy&quot; /&gt;
      );
  }
  </code></pre>
  <p>So the question is, how do I create and access the cytoscape object (and modify its nodes and elements) inside a react functional component?</p>