In this blog, I’ll share my experience using the why-did-you-render
package to debug and optimize React performance.
You know, one of the main reasons why the React application is slow is that it renders too much and unnecessarily. Usually, it is hard to detect, especially in large, complex applications.
why-did-you-render
why-did-you-render
is a lightweight debugging tool that logs unnecessary re-renders in the console. It works by attaching itself to React and monitoring component updates.
Installation
yarn add @welldone-software/why-did-you-render
Enabling It in Your App
Next, modify your index.js or App.js file to enable why-did-you-render in development mode:
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
if (process.env.NODE_ENV === "development") {
const whyDidYouRender = require("@welldone-software/why-did-you-render");
whyDidYouRender(React, {
trackAllPureComponents: true, // Track all memoized components
});
}
ReactDOM.render(<App />, document.getElementById("root"));
This setup ensures that why-did-you-render only runs in development mode, preventing unnecessary logs in production.
Debugging the Re-renders
Once enabled, I started seeing logs in the browser console whenever a component re-rendered unnecessarily.
Component <Counter> re-rendered because of props changes: { count: 0 }
To further investigate, I explicitly marked components for tracking by adding whyDidYouRender properties:
import React from "react";
const Counter = React.memo(({ count }) => {
console.log("Counter rendered");
return <p>Count: {count}</p>;
});
Counter.whyDidYouRender = true; // Enable tracking for this component
export default Counter;
Now, the console clearly showed if the Counter component re-rendered unnecessarily.
Conclusion
Using why-did-you-render, I was able to pinpoint and eliminate unnecessary renders in my React application. It’s an invaluable tool when debugging performance issues, and I highly recommend adding it to your workflow.