去抖動和限制是透過控制函數執行頻率來回應頻繁事件(例如,打字、滾動、調整大小)來最佳化效能的技術。
去抖動會延遲函數的執行,直到自上次呼叫函數以來經過一定時間後。
import React, { useState, useEffect } from 'react'; const DebouncedSearch = () => { const [searchTerm, setSearchTerm] = useState(''); const [debouncedValue, setDebouncedValue] = useState(''); useEffect(() => { const handler = setTimeout(() => { setDebouncedValue(searchTerm); }, 500); // Delay of 500ms return () => { clearTimeout(handler); // Cleanup on input change }; }, [searchTerm]); useEffect(() => { if (debouncedValue) { console.log('API Call with:', debouncedValue); // Make API call here } }, [debouncedValue]); return ( <input type="text" placeholder="Search..." value={searchTerm} onChange={(e) => setSearchTerm(e.target.value)} /> ); }; export default DebouncedSearch;
限制可確保函數在指定的時間間隔內最多執行一次,無論函數在該時間間隔內被觸發多少次。
import React, { useEffect } from 'react'; const ThrottledScroll = () => { useEffect(() => { const handleScroll = throttle(() => { console.log('Scroll event fired'); }, 1000); // Execute at most once every 1000ms window.addEventListener('scroll', handleScroll); return () => { window.removeEventListener('scroll', handleScroll); }; }, []); return <div> <hr> <h3> <strong>3. Using Libraries (Optional)</strong> </h3> <p>Instead of implementing custom debounce/throttle, you can use popular libraries like:</p> <h4> <strong>Lodash</strong> </h4> <p>Install:<br> </p> <pre class="brush:php;toolbar:false">npm install lodash
用法:
import { debounce, throttle } from 'lodash'; // Debounce Example const debouncedFunc = debounce(() => console.log('Debounced!'), 500); // Throttle Example const throttledFunc = throttle(() => console.log('Throttled!'), 1000);
安裝:
npm install react-use
用法:
import { useDebounce, useThrottle } from 'react-use'; const Demo = () => { const [value, setValue] = useState(''); const debouncedValue = useDebounce(value, 500); const throttledValue = useThrottle(value, 1000); useEffect(() => { console.log('Debounced:', debouncedValue); console.log('Throttled:', throttledValue); }, [debouncedValue, throttledValue]); return ( <input value={value} onChange={(e) => setValue(e.target.value)} placeholder="Type something..." /> ); }; export default Demo;
Feature | Debouncing | Throttling |
---|---|---|
Execution | Executes once after the user stops firing events for a specified time. | Executes at regular intervals during the event. |
Use Cases | Search input, resizing, form validation. | Scroll events, button clicks, API polling. |
Performance | Reduces the number of function calls. | Limits execution to once per interval. |
以上是透過在reactjs中使用去抖動/節流技術來減少伺服器負載的詳細內容。更多資訊請關注PHP中文網其他相關文章!