title: How can I debounce editor value when the value is managed by parent component?
body: <p>Editor component</p>
  <pre><code>import Editor from '@monaco-editor/react';
  import { useDebounce } from './useDebounce';
  import { useEffect, useState } from 'react';
  
  type Props = {
    code: string;
    onChange: (code: string) =&gt; void;
    disabled?: boolean;
  };
  
  export const GraphqlCodeEditor = ({
    onChange,
    code,
    disabled = false,
  }: Props) =&gt; {
    const [editorValue, setEditorValue] = useState(code);
    const editorValueDebounced = useDebounce(editorValue, 500);
  
    useEffect(() =&gt; {
      onChange(editorValueDebounced);
    }, [editorValueDebounced, onChange]);
  
    useEffect(() =&gt; {
      if (code !== editorValueDebounced) {
        setEditorValue(code);
      }
    }, [code, editorValueDebounced]);
  
    return (
      &lt;Editor
        options={{
          minimap: { enabled: false },
          autoClosingBrackets: 'always',
          readOnly: disabled,
        }}
        language=&quot;graphql&quot;
        value={editorValue}
        onChange={(value) =&gt; {
          if (value) {
            setEditorValue(value);
          }
        }}
      /&gt;
    );
  };
  </code></pre>
  <p>useDebounce hook</p>
  <pre><code>import { useEffect, useState } from 'react';
  
  export const useDebounce = &lt;T&gt;(value: T, delay: number) =&gt; {
    // State and setters for debounced value
    const [debouncedValue, setDebouncedValue] = useState(value);
    useEffect(
      () =&gt; {
        // Update debounced value after delay
        const handler = setTimeout(() =&gt; {
          setDebouncedValue(value);
        }, delay);
        // Cancel the timeout if value changes (also on delay change or unmount)
        // This is how we prevent debounced value from updating if value is changed ...
        // .. within the delay period. Timeout gets cleared and restarted.
        return () =&gt; {
          clearTimeout(handler);
        };
      },
      [value, delay] // Only re-call effect if value or delay changes
    );
    return debouncedValue;
  };
  </code></pre>
  <p>The code prop in the editor component is managed by a parent component. When e.g a user loads a new code snippet it's updated and the editor should load the new value. The editor should also debounce it's value so the onChange() function isn't called on every keypress.</p>
  <p>The editor component above results in a loop where the component switches between the previous value and the new every 500ms.</p>
  <p>How can I achieve this with the useDebounce hook?</p>
  <p>This is closely related to this <a href="https://stackoverflow.com/questions/58231312/input-doesnt-work-when-used-with-debounce-event-persist-and-storing-value-at">post</a> I think, however it's using lodash debounce. I was hoping to achieve the same with the useDebounce hook.</p>