I need the state to change to maintain the string the user is typing. However I want to delay an action until the user stops typing. But I can\'t quite place my finger on how to
Actually, I have the same issue but a little setTimeout
could help me with a check ref
for the first time mount:
import React, {useState, useEffect, useRef} from "react";
const Search = () => {
const filterRef = useRef(); // use ref to call the API call all time except first time
const [serpQuery, setSerpQuery] = useState('');
useEffect(() => {
let delayTimeOutFunction;
if(!filterRef.current) {
filterRef.current = true;
} else { // componentDidMount equivalent
delayTimeOutFunction = setTimeout(() => {
console.log('call api: ', serpQuery)
}, 700); // denounce delay
}
return () => clearTimeout(delayTimeOutFunction);
}, [serpQuery]);
return (
setSerpQuery(e.target.value)} />
);
};