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

React无状态组件:函数组件与PureComponent哪个更优?

无状态组件:函数组件 vs React.PureComponent 怎么选?

Great question! When building stateless components in React, choosing between functional components and React.PureComponent depends mostly on your performance needs and coding preferences. Let’s break down the key differences and best use cases clearly:

1. 函数组件(Functional Component)

  • 本质是纯函数,接收props并返回JSX。传统无场景下它没有内部状态(不过现在用Hooks也能给函数组件加状态)。
  • 默认无props对比逻辑:只要父组件重新渲染,不管props有没有变化,函数组件都会跟着重新渲染。
  • 代码简洁易写,就像你给出的示例这样:
import React from 'react';
export default function Example(props){
  return (
    <div>
      {props.myProps}
    </div>
  )
}
  • 适用场景:
    • 简单的展示型组件,props不常变化的情况。
    • 不需要做性能优化的场景——额外的对比逻辑反而会增加代码复杂度。
    • (补充:如果之后需要优化,用React.memo包裹函数组件,就能实现类似PureComponent的浅对比效果)

2. React.PureComponent

  • 属于类组件的一种,继承自React.Component,但内置了shouldComponentUpdate的浅比较逻辑。
  • 只有当props(或state,无状态场景下只看props)发生浅变化时,才会触发重新渲染。
  • 代码比函数组件稍繁琐,示例如下:
import React from 'react';
export default class Example extends React.PureComponent {
  render() {
    return(
      <div>
        {this.props.myProps}
      </div>
    )
  }
}
  • 适用场景:
    • 会被频繁触发渲染,但props大多时候不会变化的组件(比如长列表里的列表项)。
    • 需要避免不必要的重渲染来提升性能的场景。
    • ⚠️ 注意:如果props是嵌套对象、数组这类复杂数据,浅比较会失效。这时要么手动实现shouldComponentUpdate做深比较,要么用不可变数据结构确保内容变化时引用也跟着变。

最终建议

  • 如果组件逻辑简单、props不常变,优先选函数组件——代码更清爽,维护成本更低。
  • 当你发现组件有不必要的重渲染导致性能问题,或者明确知道组件会被频繁渲染但props稳定时,再用React.PureComponent(或者用React.memo包裹函数组件,是更现代的替代方案)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 07:04:21