title: Should Javascript ES6 Classes be Used as React State?
body: <p>Should ES6 classes be used directly as React state?</p>
  
  <p>I want to define an ES6 class that:  </p>
  
  <ol>
  <li>Has member variables that will be displayed on the frontend. (changes to them trigger re-renders) </li>
  <li>Has methods that sync those member variables with my backend periodically as they change. </li>
  </ol>
  
  <p>However, calling <code>setState</code> does not appear to diff class members, at least as far as I can tell. </p>
  
  <p>Using the following class:</p>
  
  <pre class="lang-js prettyprint-override"><code>class Document{
    constructor(){
      this.title = "";
      this.body = "";
    }
  
  
    syncWithDatabase = async () =&gt; {
      // do some logic to update the database 
    }
  
  }
  </code></pre>
  
  <p>And this component:</p>
  
  <pre class="lang-js prettyprint-override"><code>
  // import Document from "...";
  
  export default function Sandbox() {
    const [document, setDocument] = useState(new Document());
    const [renderTrigger, setRenderTrigger] = useState(false);
  
    return (
      &lt;div&gt;
        &lt;div&gt;{document.title}&lt;/div&gt;
        &lt;div&gt;{document.body}&lt;/div&gt;
        &lt;button
          onClick={() =&gt; {
            document.title = 'Some Default Title';
            document.body = 'lorem text';
            document.syncWithDatabase(); // being able to take this type of action in this way is why I'm trying to use classes. 
            setDocument(document);
          }}
        &gt;
          Set Canned Data
        &lt;/button&gt;
  
        &lt;div&gt;Render trigger is: {renderTrigger ? 'true' : 'false'}&lt;/div&gt;
        &lt;button onClick={() =&gt; setRenderTrigger(true)}&gt;Force Render&lt;/button&gt;
  
     &lt;/div&gt;
    );
  }
  </code></pre>
  
  <p>Clicking the first button will set the title and body on the instance of <code>Document</code> held react state, but it <strong>will not</strong> update the UI. </p>
  
  <p>Clicking the second button to force a re-render in a way that I am confident will work makes the updated members of <code>document</code> render out, even though they didn't when <code>setDocument</code> is called. </p>
  
  <p>Creating a new object with <code>new Document()</code> and passing it <code>setDocument</code> <strong>WILL</strong> trigger a re-render. So I'm thinking that react isn't doing a deep compare or is seeing that the reference to the <code>Document</code> object has not changed, and therefore not re-rending. </p>
  
  <p>So, is it possible to change an object's members, pass that object to a setState hook and have it update the UI, without creating an entirely new object? Or should I avoid doing what I'm trying to do here?</p>