{"id":13400325,"url":"https://github.com/welldone-software/why-did-you-render","last_synced_at":"2025-05-12T18:46:54.122Z","repository":{"id":37382229,"uuid":"157014461","full_name":"welldone-software/why-did-you-render","owner":"welldone-software","description":"why-did-you-render by Welldone Software monkey patches React to notify you about potentially avoidable re-renders. (Works with React Native as well.)","archived":false,"fork":false,"pushed_at":"2025-04-15T12:00:24.000Z","size":8444,"stargazers_count":11869,"open_issues_count":35,"forks_count":212,"subscribers_count":39,"default_branch":"master","last_synced_at":"2025-05-05T16:04:14.462Z","etag":null,"topics":["component","hooks-tracking","performance","pure","purecomponent","react","react-native","render","tool","update"],"latest_commit_sha":null,"homepage":"https://www.npmjs.com/package/@welldone-software/why-did-you-render","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/welldone-software.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2018-11-10T19:31:09.000Z","updated_at":"2025-05-05T13:59:27.000Z","dependencies_parsed_at":"2023-02-08T06:15:53.063Z","dependency_job_id":"8e01a517-dbab-4be9-92ad-70acc9bcb238","html_url":"https://github.com/welldone-software/why-did-you-render","commit_stats":{"total_commits":397,"total_committers":39,"mean_commits":"10.179487179487179","dds":0.1511335012594458,"last_synced_commit":"6cfbf2c31bd943facb87ea02c3ee3a7df6d41631"},"previous_names":[],"tags_count":109,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/welldone-software%2Fwhy-did-you-render","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/welldone-software%2Fwhy-did-you-render/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/welldone-software%2Fwhy-did-you-render/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/welldone-software%2Fwhy-did-you-render/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/welldone-software","download_url":"https://codeload.github.com/welldone-software/why-did-you-render/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":252940932,"owners_count":21828769,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["component","hooks-tracking","performance","pure","purecomponent","react","react-native","render","tool","update"],"created_at":"2024-07-30T19:00:50.678Z","updated_at":"2025-05-12T18:46:54.026Z","avatar_url":"https://github.com/welldone-software.png","language":"JavaScript","funding_links":[],"categories":["Uncategorized","Dev Tools","JavaScript","React Development Tools","📖 Categories","React","Development Tools","Developer Tools","目录","React [🔝](#readme)"],"sub_categories":["Uncategorized","Performance","Development Tools","Build","Parsing"],"readme":"\u003cp align=\"center\"\u003e\n  \u003cimg src=\"images/WDYR-logo.jpg\" width=\"300px\" /\u003e\n\u003c/p\u003e\n\n# Why Did You Render\n\n[![npm version](https://badge.fury.io/js/%40welldone-software%2Fwhy-did-you-render.svg)](https://badge.fury.io/js/%40welldone-software%2Fwhy-did-you-render)\n[![Build Status](https://github.com/welldone-software/why-did-you-render/actions/workflows/main.yml/badge.svg)](https://github.com/welldone-software/why-did-you-render/actions/workflows/main.yml)\n[![license](https://img.shields.io/npm/l/@welldone-software/why-did-you-render?style=flat)](https://github.com/welldone-software/why-did-you-render/blob/master/LICENSE)\n[![@welldone-software/why-did-you-render](https://snyk.io/advisor/npm-package/@welldone-software/why-did-you-render/badge.svg)](https://snyk.io/advisor/npm-package/@welldone-software/why-did-you-render)\n[![Coverage Status](https://coveralls.io/repos/github/welldone-software/why-did-you-render/badge.svg?branch=add-e2e-tests-using-cypress)](https://coveralls.io/github/welldone-software/why-did-you-render?branch=add-e2e-tests-using-cypress)\n\n`why-did-you-render` by [Welldone Software](https://welldone.software/) monkey patches **`React`** to notify you about potentially avoidable re-renders. (Works with **`React Native`** as well.)\n\nFor example, if you pass `style={{width: '100%'}}` to a big memo component it would always re-render on every element creation:\n```jsx\n\u003cMemoBigList style={{width: '100%'}}/\u003e\n```\nIt can also help you to simply track when and why a certain component re-renders.\n\n\u003e [!CAUTION]\n\u003e The library was not tested with [React Compiler](https://react.dev/learn/react-compiler) at all. I believe it's completely incompatible with it.\n\n\u003e [!CAUTION]\n\u003e Not all re-renders are *\"bad\"*. Sometimes shenanigan to reduce re-renders can either hurt your App's performance or have a negligible effect, in which case it would be just a waste of your efforts, and complicate your code. Try to focus on heavier components when optimizing and use the [React DevTools Profiler](https://legacy.reactjs.org/blog/2018/09/10/introducing-the-react-profiler.html) to measure the effects of any changes.\n\n\u003e [!NOTE]\nI've joined the React team, specifically working on React tooling. This role has opened up exciting opportunities to enhance the developer experience for React users— and your input could offer valuable insights to help me with this effort. Please join the conversation in the [discussion thread](https://github.com/welldone-software/why-did-you-render/discussions/309)!\n\n## Setup\nThe latest version of the library was tested [(unit tests and E2E)]((https://travis-ci.com/welldone-software/why-did-you-render.svg?branch=master)) with **`React@19`** only.\n* [For `React 18`, please see the readme for version @^8](https://github.com/welldone-software/why-did-you-render/tree/version-8).\n* [For `React 17` and `React 16`, please see the readme for version @^7](https://github.com/welldone-software/why-did-you-render/tree/version-7).\n\n```\nnpm install @welldone-software/why-did-you-render --save-dev\n```\nor\n```\nyarn add @welldone-software/why-did-you-render -D\n```\nSet the library to be the React's importSource and make sure `preset-react` is in `development` mode.\n\nThis is because `React 19` requires using the `automatic` [JSX transformation](https://legacy.reactjs.org/blog/2020/09/22/introducing-the-new-jsx-transform.html). \n```js\n['@babel/preset-react', {\n  runtime: 'automatic',\n  development: process.env.NODE_ENV === 'development',\n  importSource: '@welldone-software/why-did-you-render',\n}]\n```\n\n### React Native\n\n#### Bare workflow\n\nAdd the plugin as listed below and start react-native packager as usual. Default env for babel is \"development\". If you do not use expo when working with react-native, the following method will help you.\n\n```js\nmodule.exports = {\n  presets: ['module:metro-react-native-babel-preset'],\n\n  env: {\n    development: {\n      plugins: [['@babel/plugin-transform-react-jsx', {\n        runtime: 'automatic',\n        development: process.env.NODE_ENV === 'development',\n        importSource: '@welldone-software/why-did-you-render',\n      }]],\n    },\n  },\n}\n```\n\n#### Expo managed\n\nYou can pass params to `@babel/preset-react` through `babel-preset-expo`\n\n```js\n// babel.config.js\nmodule.exports = function (api) {\n  api.cache(true);\n  return {\n    presets: [\n      [\n        \"babel-preset-expo\",\n        {\n          jsxImportSource: \"@welldone-software/why-did-you-render\",\n        },\n      ],\n    ],\n  };\n};\n```\n\n\u003e Notice: Create React App (CRA) ^4 **uses the `automatic` JSX transformation.**\n\u003e [See the following comment on how to do this step with CRA](https://github.com/welldone-software/why-did-you-render/issues/154#issuecomment-773905769)\n\nCreate a `wdyr.js` file and import it as **the very first import** in your application.\n\n`wdyr.js`:\n```jsx\nimport React from 'react';\n\nif (process.env.NODE_ENV === 'development') {\n  const whyDidYouRender = require('@welldone-software/why-did-you-render');\n  whyDidYouRender(React, {\n    trackAllPureComponents: true,\n  });\n}\n```\n\n\u003e [!CAUTION]\n\u003e The library should *NEVER* be used in production because:\n\u003e - It significantly slows down React\n\u003e - It monkey patches React and can result in unexpected behavior\n\nIn [Typescript](https://github.com/welldone-software/why-did-you-render/issues/161), call the file wdyr.ts and add the following line to the top of the file to import the package's types:\n```tsx\n/// \u003creference types=\"@welldone-software/why-did-you-render\" /\u003e\n```\n\nImport `wdyr` as the first import (even before `react-hot-loader` if you use it):\n\n`index.js`:\n\n```jsx\nimport './wdyr'; // \u003c--- first import\n\nimport 'react-hot-loader';\n\nimport React from 'react';\nimport ReactDOM from 'react-dom';\n// ...\nimport {App} from './app';\n// ...\nReactDOM.render(\u003cApp/\u003e, document.getElementById('root'));\n```\n\nIf you use `trackAllPureComponents`, all pure components ([React.PureComponent](https://reactjs.org/docs/react-api.html#reactpurecomponent) or [React.memo](https://reactjs.org/docs/react-api.html#reactmemo)) will be tracked.\n\nOtherwise, add `whyDidYouRender = true` to ad-hoc components to track them. (f.e `Component.whyDidYouRender = true`)\n\nMore information about what is tracked can be found in [Tracking Components](#tracking-components).\n\nCan't see any WDYR logs? Check out the [troubleshooting section](#troubleshooting) or search in the [issues](https://github.com/welldone-software/why-did-you-render/issues).\n\n## Custom Hooks\n\nAlso, tracking custom hooks is possible by using `trackExtraHooks`. For example if you want to track `useSelector` from React Redux:\n\n`wdyr.js`:\n```jsx\nimport React from 'react';\n\n// For react-native you might want to use \n// the __DEV__ flag instead of process.env.NODE_ENV === 'development'\nif (process.env.NODE_ENV === 'development') {\n  const whyDidYouRender = require('@welldone-software/why-did-you-render');\n  const ReactRedux = require('react-redux');\n  whyDidYouRender(React, {\n    trackAllPureComponents: true,\n    trackExtraHooks: [\n      [ReactRedux, 'useSelector']\n    ]\n  });\n}\n```\n\n\u003e Notice that there's currently a problem with rewriting exports of imported files in `webpack`. A quick workaround can help with it: [#85 - trackExtraHooks cannot set property](https://github.com/welldone-software/why-did-you-render/issues/85).\n\n## Read More\n* [Why Did You Render Mr. Big Pure React Component???](http://bit.ly/wdyr1)\n* [**Common fixing scenarios** this library can help with](http://bit.ly/wdyr02)\n* [**React Hooks** - Understand and fix hooks issues](http://bit.ly/wdyr3)\n* [Why Did You Render v4 Released!](https://medium.com/welldone-software/why-did-you-render-v4-released-48e0f0b99d4c) - TypeScript support, Custom hooks tracking (like React-Redux’s useSelector), Tracking of all pure components.\n\n## Integration With Other Libraries\n* [Next.js example](https://github.com/zeit/next.js/tree/canary/examples/with-why-did-you-render)\n* [React-Redux With Hooks](https://medium.com/welldone-software/why-did-you-render-v4-released-48e0f0b99d4c)\n* [Mobx is currently not supported](https://github.com/welldone-software/why-did-you-render/issues/162)\n* [React-Native flipper plugin made by @allen-hsu](https://github.com/allen-hsu/wdyr-flipper#wdry-flipper-reporter)\n\n## Sandbox\nYou can test the library in [the official sandbox](http://bit.ly/wdyr-sb).\n\nAnd another [official sandbox with hooks tracking](https://codesandbox.io/s/why-did-you-render-sandbox-with-hooks-pyi14)\n\n## Tracking Components\nYou can track all pure components ([React.PureComponent](https://reactjs.org/docs/react-api.html#reactpurecomponent) or [React.memo](https://reactjs.org/docs/react-api.html#reactmemo)) using the `trackAllPureComponents: true` option.\n\nYou can also manually track any component you want by setting `whyDidYouRender` on them like this:\n```js\nclass BigList extends React.Component {\n  static whyDidYouRender = true\n  render(){\n    return (\n      //some heavy render you want to ensure doesn't happen if its not necessary\n    )\n  }\n}\n```\n\nOr for functional components:\n\n```js\nconst BigListPureComponent = props =\u003e (\n  \u003cdiv\u003e\n    //some heavy component you want to ensure doesn't happen if its not necessary\n  \u003c/div\u003e\n)\nBigListPureComponent.whyDidYouRender = true\n```\n\nYou can also pass an object to specify more advanced tracking settings:\n\n```js\nEnhancedMenu.whyDidYouRender = {\n  logOnDifferentValues: true,\n  customName: 'Menu'\n}\n```\n\n- `logOnDifferentValues`:\n\n  Normally, only re-renders that are caused by equal values in props / state trigger notifications:\n  ```js\n  render(\u003cMenu a={1}/\u003e)\n  render(\u003cMenu a={1}/\u003e)\n  ```\n  This option will trigger notifications even if they occurred because of different props / state (Thus, because of \"legit\" re-renders):\n  ```js\n  render(\u003cMenu a={1}/\u003e)\n  render(\u003cMenu a={2}/\u003e)\n  ```\n\n- `customName`:\n\n  Sometimes the name of the component can be missing or very inconvenient. For example:\n\n  ```js\n  withPropsOnChange(withPropsOnChange(withStateHandlers(withPropsOnChange(withState(withPropsOnChange(lifecycle(withPropsOnChange(withPropsOnChange(onlyUpdateForKeys(LoadNamespace(Connect(withState(withState(withPropsOnChange(lifecycle(withPropsOnChange(withHandlers(withHandlers(withHandlers(withHandlers(Connect(lifecycle(Menu)))))))))))))))))))))))\n  ```\n\n## Options\nOptionally you can pass in `options` as the second parameter. The following options are available:\n- `include: [RegExp, ...]` (`null` by default)\n- `exclude: [RegExp, ...]` (`null` by default)\n- `trackAllPureComponents: false`\n- `trackHooks: true`\n- `trackExtraHooks: []`\n- `logOwnerReasons: true`\n- `logOnDifferentValues: false`\n- `hotReloadBufferMs: 500`\n- `onlyLogs: false`\n- `collapseGroups: false`\n- `titleColor`\n- `diffNameColor`\n- `diffPathColor`\n- `textBackgroundColor`\n- `notifier: ({Component, displayName, hookName, prevProps, prevState, prevHookResult, nextProps, nextState, nextHookResult, reason, options, ownerDataMap}) =\u003e void`\n- `getAdditionalOwnerData: (element) =\u003e {...}`\n\n#### include / exclude\n##### (default: `null`)\n\nYou can include or exclude tracking of components by their displayName using the `include` and `exclude` options.\n\nFor example, the following code is used to [track all redundant re-renders that are caused by older React-Redux](http://bit.ly/wdyr04):\n```js\nwhyDidYouRender(React, { include: [/^ConnectFunction/] });\n```\n\u003e *Notice: **exclude** takes priority over both `include` and manually set `whyDidYouRender = `*\n\n#### trackAllPureComponents\n##### (default: `false`)\n\nYou can track all pure components (both `React.memo` and `React.PureComponent` components)\n\n\u003e *Notice: You can exclude the tracking of any specific component with `whyDidYouRender = false`*\n\n#### trackHooks\n##### (default: `true`)\n\nYou can turn off tracking of hooks changes.\n\n[Understand and fix hook issues](http://bit.ly/wdyr3).\n\n#### trackExtraHooks\n##### (default: `[]`)\n\nTrack custom hooks:\n\n```js\nwhyDidYouRender(React, {\n  trackExtraHooks: [\n    // notice that 'useSelector' is a named export\n    [ReactRedux, 'useSelector'],\n  ]\n});\n```\n\n\u003e This feature is rewriting exports of imported files. There is currently a problem with that approach in webpack. A workaround is available here: [#85 - trackExtraHooks cannot set property](https://github.com/welldone-software/why-did-you-render/issues/85)\n\n#### logOwnerReasons\n##### (default: `true`)\n\nOne way of fixing re-render issues is preventing the component's owner from re-rendering.\n\nThis option is `true` by default and it lets you view the reasons why an owner component re-renders.\n\n![demo](images/logOwnerReasons.png)\n\n#### logOnDifferentValues\n##### (default: `false`)\n\nNormally, you only want logs about component re-renders when they could have been avoided.\n\nWith this option, it is possible to track all re-renders.\n\nFor example:\n```js\nrender(\u003cBigListPureComponent a={1}/\u003e)\nrender(\u003cBigListPureComponent a={2}/\u003e)\n// will only log if you use {logOnDifferentValues: true}\n```\n\n#### hotReloadBufferMs\n##### (default: `500`)\n\nTime in milliseconds to ignore updates after a hot reload is detected.\n\nWhen a hot reload is detected, we ignore all updates for `hotReloadBufferMs` to not spam the console.\n\n#### onlyLogs\n##### (default: `false`)\n\nIf you don't want to use `console.group` to group logs you can print them as simple logs.\n\n#### collapseGroups\n##### (default: `false`)\n\nGrouped logs can be collapsed.\n\n#### titleColor / diffNameColor / diffPathColor / textBackgroundColor\n##### (default titleColor: `'#058'`)\n##### (default diffNameColor: `'blue'`)\n##### (default diffPathColor: `'red'`)\n##### (default textBackgroundColor: `'white`)\n\nControls the colors used in the console notifications\n\n#### notifier\n##### (default: defaultNotifier that is exposed from the library)\n\nYou can create a custom notifier if the default one does not suite your needs.\n\n#### getAdditionalOwnerData\n##### (default: `undefined`)\nYou can provide a function that harvests additional data from the original react element. The object returned from this function will be added to the ownerDataMap which can be accessed later within your notifier function override.\n\n## Troubleshooting\n\n### No tracking\n* If you are in production, WDYR is probably disabled.\n* Maybe no component is tracked\n    * Check out [Tracking Components](#tracking-components) once again.\n* If you only track pure components using `trackAllPureComponents: true` then you would only track either ([React.PureComponent](https://reactjs.org/docs/react-api.html#reactpurecomponent) or [React.memo](https://reactjs.org/docs/react-api.html#reactmemo)), maybe none of your components are pure so none of them will get tracked.\n* Maybe you have no issues\n    * Try causing an issue by temporary rendering the whole app twice in it's entry point:\n\n        `index.js`:\n        ```jsx\n        const HotApp = hot(App);\n        HotApp.whyDidYouRender = true;\n        ReactDOM.render(\u003cHotApp/\u003e, document.getElementById('root'));\n        ReactDOM.render(\u003cHotApp/\u003e, document.getElementById('root'));\n        ```\n\n### Custom Hooks tracking (like useSelector)\nThere's currently a problem with rewriting exports of imported files in `webpack`. A quick workaround can help with it: [#85 - trackExtraHooks cannot set property](https://github.com/welldone-software/why-did-you-render/issues/85).\n\n### React-Redux `connect` HOC is spamming the console\nSince `connect` hoists statics, if you add WDYR to the inner component, it is also added to the HOC component where complex hooks are running.\n\nTo fix this, add the `whyDidYouRender = true` static to a component after the connect:\n```js\n  const SimpleComponent = ({a}) =\u003e \u003cdiv data-testid=\"foo\"\u003e{a.b}\u003c/div\u003e)\n  // not before the connect:\n  // SimpleComponent.whyDidYouRender = true\n  const ConnectedSimpleComponent = connect(\n    state =\u003e ({a: state.a})\n  )(SimpleComponent)\n  // after the connect:\n  SimpleComponent.whyDidYouRender = true\n```\n\n### Sourcemaps\nTo see the library's sourcemaps use the [source-map-loader](https://webpack.js.org/loaders/source-map-loader/).\n\n## Credit\n\nInspired by the following previous work:\n\n* github.com/maicki/why-did-you-update (no longer public) which I had the chance to maintain for some time.\n* https://github.com/garbles/why-did-you-update where [A deep dive into React perf debugging](https://benchling.engineering/a-deep-dive-into-react-perf-debugging-fd2063f5a667/) is credited for the idea.\n\n## License\n\nThis library is [MIT licensed](./LICENSE).\n\n[🔼Back to top!](#Why-Did-You-Render)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fwelldone-software%2Fwhy-did-you-render","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fwelldone-software%2Fwhy-did-you-render","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fwelldone-software%2Fwhy-did-you-render/lists"}