Consider the overly simplified situation:
const [name, setName] = useState("");
const [check, setCheck] = useState(false);
useEffect(() => {
requestSomethingToAServer(check, name);
}, [check, name]);
return (
<div>
<input type="text" value={name} onChange={(e) => setName(e.target.value)} />
<input type="checkbox" checked={check} onChange={(e) => setCheck(e.target.checked)} />
</div>
);
Let’s say I need that request to be send whenever "check" changes it’s value, but not for every letter the user types in. How do I do that? Is there a way to tell useEffect "hey, keep an eye on this variable but do not run if it changes it value"?
I’ve been looking for new versions of react to introduce something like this in some new version, but it never happens, and there is AFAIK no straightforward way to determine which variables were updated to write a condition, and prevent the execution if it doesn’t fulfill that condition.
In a situation like these, the only solution I know is to remove "name" from the dependency array, and either ignore the warning about it, or add the comment to tell eslint to ignore the warning, but both of these sucks.
Not only there is the chance of useEffect not catching the right value of name at the moment of firing, but further changes to the logic may introduce new variables that I might miss to include as dependencies, but without the warning, it might be difficult to realize where the error is.
Is there a right way to acomplish this, like a an extra parameter or option I’m not aware about? Do you know if this is an issue for other devs? Is there feature like this on the work, or at least in the ToDo list?
Thanks.
2
Answers
You could use something like lodash debounce to avoid changing the state for every letter
You can use a timer to delay the request