Created
October 23, 2021 12:03
-
-
Save aidiary/ec2970d4e2867305b292b4568bda9272 to your computer and use it in GitHub Desktop.
キーストロークのたびに処理を実行せずに処理を遅らせる(debounce throttle)
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
useEffect(() => { | |
// 500ミリ秒後にvalidationを動かす | |
// キーストロークのたびにsetFormIsValidが呼ばれなくなる(debounce throttle) | |
// validationは軽い処理だからいいが、バックエンドにデータを送ってvalidationするような重い処理の場合に有効 | |
const identifier = setTimeout(() => { | |
setFormIsValid( | |
enteredEmail.includes('@') && enteredPassword.trim().length > 6 | |
); | |
}, 500); | |
// 2回目にuseEffect()が呼ばれたときに最初に実行されるclean up function | |
// すでに動いているTimerを削除 | |
return () => { | |
clearTimeout(identifier); | |
}; | |
}, [enteredEmail, enteredPassword]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment