Last active
November 14, 2021 04:14
-
-
Save hahuaz/d1f650b3b60d533023dc6b6746356e24 to your computer and use it in GitHub Desktop.
useEffect-with-setTimeout
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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