Have a look at this concise sandbox that mirrors the code provided below:
import React, { useState, useEffect } from "react";
import "./styles.css";
export default function App() {
let [tag, setTag] = useState(null);
function changeTagState() {
setTag(<div>I am a div</div>); //className="new"
let divTag = window.document.querySelector(`div`);
divTag.style.setProperty("color", "red");
}
return (
<>
<div onClick={changeTagState}>Click to change tag state</div>
{tag}
{/* <div onClick={alterTag}>Alter tag</div> */}
</>
);
}
Why does the variable divTag
not return null
? How is it possible for it to access and apply styles to divTag
?
This is what I expected to occur in the changeTagState
function:
setTag
is executed.- It then attempts to assign a value to
divTag
by utilizingquerySelector
. - Once
changeTagState
completes, the entire component runs again. Only then is the new value oftag
added to the DOM.