How can we stop re-rendering if the value of the useState object remains the same?
When I click on the button, the dataChange function is triggered. I am updating the useState object value; the value is the same, but the component is re-rendering on every click of the button.
const App = () => {
console.log('APP re-render :>> ', Math.random());
const [data, setData] = useState({ value:1 });
const dataChange = () => {
setData({value:1});
}
return (
<div>
<button onClick={dataChange}>Click</button>
<p>{data.value}</p>
</div>
)
}
4
Answers
You may be using the same value, but they are not the same. i.e.
If you want to use the same object, define a constant outside your component, and use that in place of
{value: 1}
:you can use use useMemo hook to avoid the rerendering
useState
is not a database, you need to add logic to compare the current state and the new state if they’re the same just return the current state else update the state . You can useuseMemo hook
like this ;To prevent a re-render when the value of the useState object remains the same, you need to check if the new state is actually different from the current state before updating it. If the state hasn’t changed, you can avoid calling the state updater function.
One way to do this is to use a functional update with setData to ensure that the new state is compared with the current state. Here’s how you can modify your dataChange function to perform this check: