React Rendering Performance
A re-render happens when React decides that a component’s output may have changed and it needs to call the component again to compute the new UI.
useState or this.setState causes a re-render.forceUpdate() in class components.React components are pure functions of props and state:
Here, updating the count state triggers a re-render on every button click.
// Counter re-renders every time its state (count) changes
import { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
console.log("Counter component re-rendered");
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
setCount(count + 1) updates the state value.Counter."Counter component re-rendered".count.When the parent’s state changes, it passes a new prop to the child, which triggers the child’s re-render.
// Child re-renders whenever the value prop coming from Parent changes
import { useState } from "react";
function Child({ value }) {
console.log("Child re-rendered");
return <p>Value: {value}</p>;
}
function Parent() {
const [num, setNum] = useState(0);
return (
<div>
<button onClick={() => setNum(num + 1)}>Update Parent</button>
<Child value={num} />
</div>
);
}
num is stored as state in Parent.num.Parent re-renders and passes a new value prop to Child.Child re-renders and logs "Child re-rendered" again.If a component keeps re-rendering even when its inputs don’t change, you can optimize it using React.memo, useCallback, and useMemo.
React.memo() to memoize components that receive unchanged props.useCallback() to avoid recreating functions on every render.useMemo() to cache expensive calculations.setCount(count)).
// MemoizedChild only re-renders when its props actually change
const MemoizedChild = React.memo(function Child({ value }) {
console.log("MemoizedChild rendered");
return <p>Value: {value}</p>;
});
Not every React re-render leads to a heavy visual repaint — React and the browser both try to minimize expensive work.
React.memo for pure components that depend only on their props.console.log("Component re-rendered") during development to understand render frequency.Parent and Child component. Log to the console when each one renders.Child in React.memo() and confirm that it only re-renders when its props change.onClick) and memoize it using useCallback.useMemo and see how it affects performance.Goal: Understand exactly what triggers React re-renders and apply memoization techniques to prevent unnecessary renders.