title: How to access current state of component from useEffect without making it a dependency?
body: <p>I've got the following component (simplified) which, given a note ID, would load and display it. It would load the note in <code>useEffect</code> and, when a different note is loaded or when the component gets unmounted, it saves the note.</p>
  
  <pre><code>const NoteViewer = (props) =&gt; {
      const [note, setNote] = useState({ title: '', hasChanged: false });
  
      useEffect(() =&gt; {
          const note = loadNote(props.noteId);
          setNote(note);
  
          return () =&gt; {
              if (note.hasChanged) saveNote(note); // bug!!
          }
      }, [props.noteId]);
  
      const onNoteChange = (event) =&gt; {
          setNote({ ...note, title: event.target.value, hasChanged: true });
      }
  
      return (
          &lt;input value={note.title} onChange={onNoteChange}/&gt;
      );
  }
  </code></pre>
  
  <p>The issue is that within the <code>useEffect</code> I use <code>note</code>, which is not part of the dependencies so it means I always get stale data.</p>
  
  <p>However, if I put the note in the dependencies then the loading and saving code will be executed whenever the note is modified, which is not what I need.</p>
  
  <p>So I'm wondering how can I access the current note, without making it a dependency? I've tried to replace the note with a ref, but it means the component no longer updates when the note is changed, and I'd rather not use references.</p>
  
  <p>Any idea what would be the best way to achieve this? Maybe some special React Hooks pattern?</p>