React函数组件使用内联函数是否会影响性能?
Great question—this is a super common point of confusion when transitioning from class components to function components, so let's unpack it step by step.
First: The Class vs. Function Component Difference
In class components, inline anonymous functions get recreated on every render, which can trigger unnecessary re-renders if passed as props to a PureComponent or memoized child (since the prop reference changes each time). That's why we were taught to define handler methods outside the render method back then.
But function components work differently: every time the component renders, the entire function body runs. Any function you define inside it—whether inline or as a named function—will be a new reference each time. So an inline onChange={(e) => setTitle(e.target.value)} is functionally no different from defining a handleChange function inside the component's body in terms of reference creation.
So Is Using Inline Functions Bad?
Most of the time, no—you can safely use inline anonymous functions. Here's why:
- Modern JavaScript engines are extremely efficient at creating and garbage-collecting small functions. The overhead is negligible for most apps, especially compared to the complexity of adding unnecessary optimizations.
- React's internal rendering pipeline is optimized to handle this kind of scenario without major performance hits.
The React docs' warning about overusing useCallback is spot-on: useCallback has its own overhead—it needs to track dependencies and maintain the cached reference. If you use it when you don't need to, you're adding extra work for React without any tangible benefit.
When Should You Optimize?
Only reach for useCallback if you have a measurable performance problem that traces back to function prop references causing unnecessary re-renders. Specifically:
- You're passing the function as a prop to a child component wrapped in
React.memo(or a similar memoization utility). - React DevTools confirms the child component is re-rendering frequently when it shouldn't, and the root cause is the changing function prop.
In those cases, wrapping the function with useCallback (and correctly specifying its dependencies) will stabilize the reference, preventing the child from re-rendering unnecessarily.
Recommended Practices
- Start with inline functions for simple cases (like your
onChangeexample). The code is concise, readable, and avoids the boilerplate of defining separate handlers or usinguseCallbackunnecessarily. - Don't optimize prematurely. Wait until you notice actual performance issues (e.g., janky UI, slow renders in specific components) before reaching for memoization tools like
useCallback. - If you do optimize, pair
useCallbackwithReact.memo. Without memoizing the child component,useCallbackwon't provide any benefit—since the child would re-render anyway when the parent does.
内容的提问来源于stack exchange,提问作者Martin

