Medium
You're implementing an auto-save feature for a document editor. During testing, you notice that the save function is being called too frequently during rapid typing. What's the best way to optimize this code?
1function DocumentEditor() {2 const [content, setContent] = useState('');3 const [saveStatus, setSaveStatus] = useState('saved');45 async function saveDocument(text) {6 setSaveStatus('saving');7 try {8 await api.saveDocument(text);9 setSaveStatus('saved');10 } catch (err) {11 setSaveStatus('error');12 }13 }1415 function handleChange(e) {16 const newContent = e.target.value;17 setContent(newContent);18 saveDocument(newContent);19 }2021 return (22 <div>23 <textarea24 value={content}25 onChange={handleChange}26 placeholder="Start typing..."27 />28 <div>Status: {saveStatus}</div>29 </div>30 );31}