the effects (increment the value of r and log it) works as expected within the useEffect hook
import React from "react";
let r = 0;
export default function App() {
const [state, setState] = React.useState(false);
function handler() {
setState(!state);
}
React.useEffect(() => {
r += 1;
console.log("rendering:-", r, " times");
});
return (
<>
<button onClick={handler}>render</button>
</>
);
}
but outside of useEffect hook the effects work unexpectedly. value of r increments by 2 rather than 1
import React from "react";
let r = 0;
export default function App() {
const [state, setState] = React.useState(false);
function handler(params) {
setState(!state);
}
r += 1;
console.log("rendering:-", r, " times");
return (
<>
<button onClick={handler}>render</button>
</>
);
}
but why??? could someone explain me please.....