So after working with react in the past year, i managed to understand its powers and caveats, and how to avoid unnecessary renders.
Yesterday i was playing with some code and came across an issue i didnt see before, and got a little confuse.
import React, { useCallback, useState } from "react";
let renders = 0;
const Counter = () => {
const [count, setCount] = useState(0);
const increment = useCallback(() => {
setCount((c) => c + 1);
}, []);
renders = renders + 1;
console.log("Counter Render");
return (
<div>
<button onClick={increment}>increment</button>
<h2>renders: {renders}</h2>
<h4>Count: {count}</h4>
</div>
);
};
export default React.memo(Counter);
in the above code i added a simple counter, on every click i am setting a new state, which cause a re-render, showing "Count: 1" on the screen and one "Counter Render" log in dev tools - just like i expected.
The weird part comes from the renders variable, which i initiate with the number 0 ( outside the component, offcourse ) and increment on every render of the component. i would have expect the value here will also be 1 but that is not the case, every time i click the button the value of "renders" grows by 2, even though the "Counter Render" log show once each time.
can anyone explain what am i missing here ?