Clean β’ Professional
React applications can sometimes experience performance issues due to unnecessary re-renders, heavy components, or inefficient state updates. Profiling helps you identify performance bottlenecks and optimize your React app for faster rendering and better user experience.
React provides React DevTools as a primary tool to profile and optimize React components.
Profiler Output Includes:
a) React.memo
Wrap components with React.memo to prevent re-renders when props donβt change
const MyComponent = React.memo(function({ data }) {
return <div>{data}</div>;
});
b) useCallback
Memoizes functions to prevent passing new function references on every render
const handleClick = useCallback(() => {
console.log("Clicked!");
}, []);
c) useMemo
Memoizes expensive computations to avoid recalculating on every render
const expensiveValue = useMemo(() => computeHeavyTask(data), [data]);
d) List Virtualization
e) Lazy Loading & Code Splitting
React.lazy and SuspenseProfiling Example
Suppose you have a component tree with multiple child components:
import React, { useState } from "react";
function Child({ value }) {
console.log("Child rendered");
return <div>{value}</div>;
}
function Parent() {
const [count, setCount] = useState(0);
return (
<div>
<Child value="Hello" />
<button onClick={() => setCount(count + 1)}>Increment</button>
<p>Count: {count}</p>
</div>
);
}
export default Parent;
Problem: Every time you increment count, the Child component also re-renders unnecessarily.
Solution: Wrap Child in React.memo():
const Child = React.memo(({ value }) => {
console.log("Child rendered");
return <div>{value}</div>;
});
Now Child only renders if value changes.