优化react组件非必要的重新渲染

重新渲染的起因:

  • 组件的state变化
  • 父组件重新渲染,导致子组件重新渲染
  • 组件使用context,provider的value发生变化时
  • hooks变化
    • hooks内的状态更改将触发不可避免的宿主重复渲染
    • 如果hooks使用了 Context 并且 Context 的值发生了变化,它会触发一个不可避免的重复渲染

渲染优化:

  • 使用memo、useMemo缓存组件
  • 向下移动状态。当前组件很重,但是有个小弹窗是当前组件控制的状态,会导致当前组件重渲染,将控制弹窗的state抽离到一个新组件中,很重的父组件就不会重渲染
  • 将组件抽离为props的children,children在子组件中不会重渲染
  • 将组件作为props传递到子组件,子组件更新不会影响到这个props组件
  • effect的依赖中有引用类型数据(对象,数组,函数等),应对这些依赖进行useMemo,useCallback
  • context不在根组件,其祖先更新会导致其更新进而导致使用该context的组件更新,应对该context使用useMemo记忆
  • 使用多层的context,外层的context变化不会影响到内层的context(同上述children)

子组件使用useContext导致的重渲染

// value是个复杂类型的对象,父组件的重渲染会导致重新生成{mode}
const ThemeContext = React.createContext<Theme>({ mode: 'light' });
const useTheme = () => {
  return useContext(ThemeContext);
};
// before:
// 父组件
const [mode, setMode] = useState<Mode>("light");
return (
    <ThemeContext.Provider value={{ mode }}>
      // 这里有个计数器点击+1
      // 这里有个按钮可以切换主题模式
    </ThemeContext.Provider>
  );
const Item = ({ country }: { country: Country }) => {
    // 父组件计数器+1,这里每次会是个新对象,导致重渲染
    const { mode } = useTheme();
    const className = `country-item ${mode === "dark" ? "dark" : ""}`;
    // the rest is the same
}

// after:
const [mode, setMode] = useState<Mode>("light");
// memoising the object! 缓存对象
  const theme = useMemo(() => ({ mode }), [mode]);
return (
    <ThemeContext.Provider value={theme}>
      <button onClick={() => setMode(mode === 'light' ? 'dark' : 'light')}>Toggle theme</button>
      // 这里有个计数器,可以点击+1
      // 这里有个按钮可以切换主题模式
    </ThemeContext.Provider>
  )
// 子组件
const Item = ({ country }: { country: Country }) => {
    // 父组件计数器+1,这里每次是个同一个theme对象,不会重渲染
    // 切换主题会导致子组件重新渲染
    const { mode } = useTheme();
    const className = `country-item ${mode === "dark" ? "dark" : ""}`;
    // the rest is the same
}

React.memo,配合useCallback将组件缓存

// props中的属性全部使用useMemo进行缓存,MovingComponent 的重渲染不会导致ChildComponent 的重渲染
// 如果props中有函数参数,在父组件中应使用useCallback包裹,以保持父组件每次重渲染时,传递给子组件的函数引用地址一致
// 如果子组件中接收的children和props是组件,则这些组件都需要memo,子组件才不会重渲染
const ChildComponent = (props) {
  ...
  return (
      <div onClick={props.onClick}>{props.a}</div>
  )
}
export default React.memo(ChildComponent)

const MovingComponent = () => {
const [state, setState] = useState({ x: 100, y: 100 });
const onClick = useCallback(() => {
    console.log('xxx')
}, [])
return (
  <div
    onMouseMove={(e) => setState({ x: e.clientX - 20, y: e.clientY - 20 })}
    style={{ left: state.x, top: state.y }}
  >
    // MovingComponent的重渲染不会导致ChildComponent 的重渲染
    <ChildComponent a={111} onClick={onClick} />
  </div>
);
};


抽离为children,以避免重渲染

# 鼠标移动后,MovingComponent 会重渲染,导致子组件ChildComponent 重渲染,如果后者很“重”,将导致性能问题
const MovingComponent = () => {
  const [state, setState] = useState({ x: 100, y: 100 });

  return (
    <div
      // when the mouse moves inside this component, update the state
      onMouseMove={(e) => setState({ x: e.clientX - 20, y: e.clientY - 20 })}
      // use this state right away - the component will follow mouse movements
      style={{ left: state.x, top: state.y }}
    >
      <ChildComponent />
    </div>
  );
};
// ChildComponent 通过children 传递,MovingComponent 的重渲染不会导致ChildComponent 重渲染,
// 因为ChildComponent 隶属于组件SomeOutsideComponent,组件作为children传递不会重渲染,因为它是props,
// 它在SomeOutsideComponent 组件中已经创建完毕,已经调用过React.createElement了
const MovingComponent = ({ children }) => {
  const [state, setState] = useState({ x: 100, y: 100 });

  return (
    <div onMouseMove={(e) => setState({ x: e.clientX - 20, y: e.clientY - 20 })} style={{ left: state.x, top: state.y }}>
      // children now will not be re-rendered
      {children}
    </div>
  );
};

const SomeOutsideComponent = () => {
  return (
    <MovingComponent>
      <ChildComponent />
    </MovingComponent>
  );
};

Mystery 1:为什么通过props传递一个组件给子组件,子组件重渲染不会使传递的组件重渲染?

why components that are passed as props don’t re-render?
Answer 1: “children” is a <ChildComponent /> element that is created in SomeOutsideComponent. When MovingComponent re-renders because of its state change, its props stay the same. Therefore any Element (i.e. definition object) that comes from props won’t be re-created, and therefore re-renders of those components won’t happen.

children即<ChildComponent />组件是在SomeOutsideComponent组件中创建的,MovingComponent state变化引起重渲染,但MovingComponent 的props与上次一样没有变化,所以任何来自props的组件(或者自定义对象)不会在MovingComponent 重渲染期间重新创建,自然也不会发生重渲染

Mystery 2: 为什么将props.children通过一个函数传递,会导致重渲染?

if children are passed as a render function, they start re-rendering. Why?

const MovingComponent = ({ children }) => {
  // this will trigger re-render
  const [state, setState] = useState();
  return (
    <div ///...
    >
      <!-- those will re-render because of the state change -->
      {children()}
    </div>
  );
};

const SomeOutsideComponent = () => {
  return (
    <MovingComponent>
      {() => <ChildComponent />}
    </MovingComponent>
  )
}

Answer 2:In this case “children” are a function, and the Element (definition object) is the result of calling this function. We call this function inside MovingComponent, i.e. we will call it on every re-render. Therefore on every re-render, we will re-create the definition object <ChildComponent />, which as a result will trigger ChildComponent’s re-render.

在这个例子中,children是个函数,并且childComponent是调用该函数的结果,MovingComponent的每次重渲染都会在组件内部调用这个函数,返回一个新的结果,所以MovingComponent的每次重渲染会导致childComponent的重渲染

Mystery 3: MovingComponentMemo使用memo,为什么没有阻止由于SomeOutsideComponent 重渲染导致ChildComponent 的重渲染

// wrapping MovingComponent in memo to prevent it from re-rendering
const MovingComponentMemo = React.memo(MovingComponent);

const SomeOutsideComponent = () => {
  // trigger re-renders here with state
  const [state, setState] = useState();

  return (
    <MovingComponentMemo>
      <!-- ChildComponent will re-render when SomeOutsideComponent re-renders -->
      <ChildComponent />
    </MovingComponentMemo>
  )
}

const MovingComponent = ({children}) => <>{children}</>

Answer 3:因为SomeOutsideComponent 的每次重渲染都重新创建了ChildComponent (是个对象),MovingComponentMemo会检查props是否变动,即检查props.children,因为ChildComponent 是重新生成的,与之前的不相等(2个对象的地址不相等),所以会触发重渲染;如果将ChildComponent 使用memo包裹,则MovingComponent的重渲染不会导致ChildComponent 重渲染,因为MovingComponent检查发现这个props与之前的相等

Mystery 4: 将Mystery 2中的函数使用useCallback包裹,还是阻止不了重渲染?

when passing children as a function, why memoizing this function doesn’t work?

const SomeOutsideComponent = () => {
  // trigger re-renders here with state
  const [state, setState] = useState();

  // this memoization doesn't prevent re-renders of ChildComponent
  const child = useCallback(() => <ChildComponent />, []);

  return <MovingComponent>{child}</MovingComponent>;
};

const MovingComponent = ({ children }) => {
  // this will trigger re-render
  const [state, setState] = useState();
  return (
    <div ///...
    >
      <!-- those will re-render because of the state change -->
      {children()}
    </div>
  );
};
child函数被记忆,但是它的返回结果(<ChildComponent />)没有被记忆,同一个函数每次都会执行React.createElement,即重渲染

参考
https://www.developerway.com/posts/react-elements-children-parents
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 193,968评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,682评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,254评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,074评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 60,964评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,055评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,484评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,170评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,433评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,512评论 2 308
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,296评论 1 325
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,184评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,545评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,880评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,150评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,437评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,630评论 2 335

推荐阅读更多精彩内容