Understanding Re-Renders
This example highlights the difference between using primitive and non-primitive values in React state management and how it affects re-rendering. When you use a primitive value (like 0), React performs a strict equality check (===), and if the value hasn't changed, it avoids unnecessary re-renders.
However, when you use a non-primitive value (like an object), even if the object properties remain the same, React will still treat it as a new object reference and trigger a re-render.
In this example, updating the state with the same object structure causes the component to re-render because React detects a new object reference, despite the object's content being identical. This demonstrates the importance of understanding how React compares state values when optimizing component performance.
import { useState } from "react";
const Six = () => {
// Primitives vs non-primitives
console.log("Component rendering..."); // this will print only when the component mounts - the first time
// this happens because comparing primitive values, we get the same value === 0
// and this won't trigger a re-render
// const [price, setPrice] = useState(0);
// but once an object is used, we get a re-render every time the button is clicked
const [price, setPrice] = useState({
number: 100,
totalPrice: true,
});
const handleClick = () => {
// setPrice(0); // setting 0 each time the button is clicked
setPrice({
number: 100,
totalPrice: true,
}); // re-render happens because this is an object
};
return (
<button
onClick={handleClick}
className="bg-blue-500 py-2 px-4 rounded text-white"
>
Click me
</button>
);
};
export default Six;