MST
星途 面试题库

面试题:React Context性能优化与Memo结合

已知React.memo可以帮助组件避免不必要的重新渲染。当在使用Context的场景下,如何有效地将React.memo与Context配合使用,以达到更好的性能优化效果?请举例说明在不同类型组件(函数组件和类组件)中具体的实现方式,并阐述需要注意的要点。
36.6万 热度难度
前端开发React

知识考点

AI 面试

面试题答案

一键面试

函数组件中React.memo与Context配合使用

  1. 创建Context
import React from 'react';
const MyContext = React.createContext();
  1. 使用React.memo包裹函数组件
const MyFunctionComponent = React.memo(({ value }) => {
  return <div>{value}</div>;
});
  1. 在函数组件中消费Context
const FunctionComponentWithContext = () => {
  const contextValue = React.useContext(MyContext);
  return <MyFunctionComponent value={contextValue} />;
};
  1. 示例完整代码
import React from'react';

const MyContext = React.createContext();

const MyFunctionComponent = React.memo(({ value }) => {
  return <div>{value}</div>;
});

const FunctionComponentWithContext = () => {
  const contextValue = React.useContext(MyContext);
  return <MyFunctionComponent value={contextValue} />;
};

const App = () => {
  const contextData = 'Hello, Context!';
  return (
    <MyContext.Provider value={contextData}>
      <FunctionComponentWithContext />
    </MyContext.Provider>
  );
};

export default App;

类组件中React.memo与Context配合使用

  1. 创建Context
import React from'react';
const MyContext = React.createContext();
  1. 类组件继承React.Component
class MyClassComponent extends React.Component {
  render() {
    return <div>{this.props.value}</div>;
  }
}
  1. 使用React.memo包裹类组件
const MemoizedClassComponent = React.memo(MyClassComponent);
  1. 在类组件中消费Context
class ClassComponentWithContext extends React.Component {
  static contextType = MyContext;
  render() {
    const contextValue = this.context;
    return <MemoizedClassComponent value={contextValue} />;
  }
}
  1. 示例完整代码
import React from'react';

const MyContext = React.createContext();

class MyClassComponent extends React.Component {
  render() {
    return <div>{this.props.value}</div>;
  }
}

const MemoizedClassComponent = React.memo(MyClassComponent);

class ClassComponentWithContext extends React.Component {
  static contextType = MyContext;
  render() {
    const contextValue = this.context;
    return <MemoizedClassComponent value={contextValue} />;
  }
}

const App = () => {
  const contextData = 'Hello, Context!';
  return (
    <MyContext.Provider value={contextData}>
      <ClassComponentWithContext />
    </MyContext.Provider>
  );
};

export default App;

注意要点

  1. Context值变化:React.memo默认只进行浅比较,若Context中的值是对象或数组,当对象或数组内部数据变化但引用不变时,React.memo包裹的组件不会重新渲染。可通过自定义比较函数(React.memo(Component, compareFunction))来处理这种情况,在比较函数中进行深比较。
  2. 性能开销:虽然React.memo可避免不必要渲染,但深比较等复杂操作本身也有性能开销,需权衡是否值得。
  3. 组件层级:若Context值在较高层级频繁变化,可能导致过多组件不必要渲染,可考虑拆分Context或使用useReducer结合Context来优化,让Context值变化更可控。