React & Modern Frontend (445 Qs)•Part 8: Advanced React Patterns, Portals & Performance (152 - 261)
How to prevent a function from being called multiple times?
If you use an event handler such as onClick or onScroll and want to prevent the callback from being fired too quickly, then you can limit the rate at which callback is executed. This can be achieved in the below possible ways,
- Throttling: Changes based on a time based frequency. For example, it can be used using _.throttle lodash function
- Debouncing: Publish changes after a period of inactivity. For example, it can be used using _.debounce lodash function
- RequestAnimationFrame throttling: Changes based on requestAnimationFrame. For example, it can be used using raf-schd lodash function
Practical Code Example
jsx
// Prevent multiple function invocations:
function SubmitButton() {
const [isSubmitting, setIsSubmitting] = useState(false);
async function handleSubmit() {
if (isSubmitting) return; // Prevent double invocation!
setIsSubmitting(true);
await api.submit();
setIsSubmitting(false);
}
return <button disabled={isSubmitting} onClick={handleSubmit}>Submit</button>;
}