Skip to content

Instantly share code, notes, and snippets.

@hahuaz
Last active November 14, 2021 04:14
Show Gist options
  • Save hahuaz/d1f650b3b60d533023dc6b6746356e24 to your computer and use it in GitHub Desktop.
Save hahuaz/d1f650b3b60d533023dc6b6746356e24 to your computer and use it in GitHub Desktop.
useEffect-with-setTimeout
import React, { useEffect } from 'react';
import { useImmer } from 'use-immer';
export default function Input() {
const [state, setState] = useImmer({
name: '',
});
const handleNameChange = (e) => {
setState((draft) => {
draft.name = e.target.value;
});
};
useEffect(() => {
if (!state.name) return;
const timeout = setTimeout(() => {
console.log('async operation...');
}, 2000);
return () => {
clearTimeout(timeout);
};
}, [state.name]);
return (
<>
<label htmlFor="name">Name:</label>
<input
value={state.name}
onChange={handleNameChange}
type="text"
id="name"
/>
</>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment