React中如何避免输入框onChange事件触发时组件重复渲染
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
userInputstate, so this re-render is necessary. React.memobenefits: If this component is used inside a parent that re-renders often (for reasons unrelated to this input),React.memowill stop this component from re-rendering unnecessarily.useCallbackbenefits: It keeps thehandleChangefunction reference stable, which is crucial if you ever pass this function as a prop to a child component (since child components usingReact.memowill rely on stable prop references to avoid re-renders).
内容的提问来源于stack exchange,提问作者Farhan Anees

