import React, { useState, useEffect, useRef } from "react";
import ReactDOM from "react-dom";
import "./styles.css";
function App() {
const [minus, setMinus] = useState(3);
const ref = useRef(null);
const handleClick = () => {
setMinus(minus - 1);
};
console.log(
"--> ref and state",
ref.current?.innerHTML ?? ref.current,
minus
);
// first useEffect
useEffect(() => {
console.log(`denp[ref.current] >`, ref.current?.innerHTML ?? ref.current);
}, [ref.current]);
// second useEffect
useEffect(() => {
console.log(`denp[minus]>`, ref.current?.innerHTML ?? ref.current);
}, [minus]);
return (
<div className="App">
{(minus >= 0 || minus <= -5) && <h1 ref={ref}>num: {minus}</h1>}
<button onClick={handleClick}>minus</button>
</div>
);
}
export default App;
On the first render: the first useEffect is run and log out: denp[ref.current] > num: 3
I press the button, the state minus is updated to 2, the component is re-rendered
On the second render: the first useEffect is run and log out: denp[ref.current] > num: 2
I press the button, the state minus is updated to 1, the component is re-rendered
On the third render: the first useEffect is not run anymore
Why the first useEffect does not run on the third render?
Live code here: https://codesandbox.io/s/brave-mayer-3f8zsl