Here is the testing code:
function Page() {
const ref = useRef(null)
const [show, setShow] = useState(false);
const [refHasValue, setRefHasValue] = useState(false);
console.log(ref, show, refHasValue);
useEffect(() => {
if (ref.current) {
setRefHasValue(true);
}
}, [ref.current]);
return (
<>
<button onClick={() => setShow(true)}>Show</button>
{show && <div ref={ref}>Hello</div>}
{refHasValue && <p>Ref has value</p>}
</>
);
}
Here is the console log result when I running this code snippet, here is the demo
{current: null} false false
(Initial Render){current: null} true false
(After I click the “Show” button){current: div} true false
(After I click the “Show” button again)
I know the logic behind the first log. It is because the element has not been initialized, also all the other two state values is false
I don’t know the logic behind the second log as well: After the click action modify the show
value to true, the DOM shows up.
But I don’t know the logic behind the third log: Why is it clickable? The state show
has been modified in the previous step, also “useEffect” has no impact here because it monitors the ref
value, so refHasValue
can not be updated. Since no state changed in this round, no render happened in the browser, why was something still printed out?