Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[React] 性能调优中,如何确定哪个数据变化引起的组件渲染【热度: 500】 #862

Open
yanlele opened this issue Aug 29, 2024 · 0 comments
Labels
web框架 web 框架相关知识 阿里巴巴 公司标签
Milestone

Comments

@yanlele
Copy link
Member

yanlele commented Aug 29, 2024

关键词:react 渲染性能调优

帮助开发者排查是哪个属性改变导致了组件的 rerender。

直接接受 ahooks 里面的一个方法: useWhyDidYouUpdate

源码实现:

import { useEffect, useRef } from "react";

export type IProps = Record<string, any>;

export default function useWhyDidYouUpdate(componentName: string, props: IProps) {
  const prevProps = useRef<IProps>({});

  useEffect(() => {
    if (prevProps.current) {
      const allKeys = Object.keys({ ...prevProps.current, ...props });
      const changedProps: IProps = {};

      allKeys.forEach((key) => {
        if (!Object.is(prevProps.current[key], props[key])) {
          changedProps[key] = {
            from: prevProps.current[key],
            to: props[key],
          };
        }
      });

      if (Object.keys(changedProps).length) {
        console.log("[why-did-you-update]", componentName, changedProps);
      }
    }

    prevProps.current = props;
  });
}
@yanlele yanlele added web框架 web 框架相关知识 阿里巴巴 公司标签 labels Aug 29, 2024
@yanlele yanlele added this to the milestone Aug 29, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
web框架 web 框架相关知识 阿里巴巴 公司标签
Projects
None yet
Development

No branches or pull requests

1 participant