首页 > web前端 > js教程 > 通过在reactjs中使用去抖动/节流技术来减少服务器负载

通过在reactjs中使用去抖动/节流技术来减少服务器负载

DDD
发布: 2025-01-15 22:33:44
原创
682 人浏览过

Decreasing server load by using debouncing/throttle technique in reactjs

React.js 中的去抖和节流

去抖动和限制是通过控制函数执行频率来响应频繁事件(例如,打字、滚动、调整大小)来优化性能的技术。


1.什么是去抖?

去抖动会延迟函数的执行,直到自上次调用函数以来经过一定时间后。

用例示例

  • 搜索输入字段:避免每次按键时触发 API 调用。

React 中的去抖动示例

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;
登录后复制

2.什么是节流?

限制可确保函数在指定的时间间隔内最多执行一次,无论该函数在该时间间隔内被触发多少次。

用例示例

  • 滚动事件:限制滚动事件期间触发函数的频率,以提高性能。

React 中的节流示例

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.
功能
去抖动

节流 标题> 执行
    在用户停止触发事件指定时间后执行一次。 活动期间定期执行。
  • 用例
  • 搜索输入、调整大小、表单验证。 滚动事件、按钮点击、API 轮询。 性能 减少函数调用次数。 将执行限制为每个时间间隔一次。 表>
  • 何时使用

    去抖动:当您想要延迟执行直到用户停止操作(例如,等待输入完成)时。 节流:当您想要控制执行速率时(例如,确保平滑的滚动性能)。 如果使用得当,这两种技术都可以显着提高性能和用户体验!

    以上是通过在reactjs中使用去抖动/节流技术来减少服务器负载的详细内容。更多信息请关注PHP中文网其他相关文章!

    本站声明
    本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
    热门教程
    更多>
    最新下载
    更多>
    网站特效
    网站源码
    网站素材
    前端模板