Skip to content

Instantly share code, notes, and snippets.

@aidiary
Created October 23, 2021 12:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aidiary/ec2970d4e2867305b292b4568bda9272 to your computer and use it in GitHub Desktop.
Save aidiary/ec2970d4e2867305b292b4568bda9272 to your computer and use it in GitHub Desktop.
キーストロークのたびに処理を実行せずに処理を遅らせる(debounce throttle)
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