You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中如何避免输入框onChange事件触发时组件重复渲染

Fixing Unnecessary Re-renders in React Input Component

Got it, let's sort out this issue. First, a quick reality check: when you type into the input, updating the userInput state will trigger a component re-render—and that's actually React's normal behavior, since we need to sync the input's displayed value with the state. The real win here is preventing unnecessary re-renders (like when a parent component re-renders for unrelated reasons) while keeping all original functionality intact.

Here's how to modify your code step by step:

Step 1: Memoize the Component with React.memo

Wrap your component in React.memo—this tells React to skip re-rendering the component if its props haven't changed. For your current component (which has no props), this prevents it from re-rendering when a parent component re-renders, even if userInput stays the same.

Step 2: Memoize the handleChange Function with useCallback

Every time your component re-renders, the handleChange function gets recreated from scratch. Using useCallback caches the function reference, so it only changes if its dependencies (in this case, setUserInput) change. This is a good practice for consistency, especially if you later add props or pass this function to child components.

Modified Code

/** 确保我们保留原有功能,同时避免在输入框中按键输入时每次都触发组件重新渲染。 */
import React, { useState, useCallback } from "react";

// 使用 React.memo 包裹组件
const ExampleComponent: React.FC = () => {
  const [userInput, setUserInput] = useState("");

  // 使用 useCallback 缓存 handleChange 函数
  const handleChange = useCallback((event: React.ChangeEvent<HTMLInputElement>) => {
    setUserInput(event.target.value);
  }, [setUserInput]); // React 保证 setUserInput 的引用稳定,所以依赖项只有它

  console.log("Example renders");
  return (
    <>
      <h1>Send us some feedback</h1>
      <div>
        <input type="text" onChange={handleChange} value={userInput} />
        <button
          type="submit"
          onClick={() => {
            alert(userInput);
          }}
        >
          Submit
        </button>
      </div>
    </>
  );
};

// 导出 memoized 后的组件
export const Example = React.memo(ExampleComponent);

Key Notes

  • Input typing still triggers re-renders: This is intentional! We need to update the input's value to match the userInput state, so this re-render is necessary.
  • React.memo benefits: If this component is used inside a parent that re-renders often (for reasons unrelated to this input), React.memo will stop this component from re-rendering unnecessarily.
  • useCallback benefits: It keeps the handleChange function reference stable, which is crucial if you ever pass this function as a prop to a child component (since child components using React.memo will rely on stable prop references to avoid re-renders).

内容的提问来源于stack exchange,提问作者Farhan Anees

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 20:37:28