React only re-renders when there is a change in state.
So why is that I see the changes I have made to real DOM directly?
I understand I am modifying the real DOM, but what is triggering the re-render when I have not changed the state at all.
import React from "react";
import ReactDOM from "react-dom";
import "./styles.css";
function App() {
return (
<div className="App">
<h1 id="header">Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
document.getElementById("header").style.color = "red";
Sanbox url https://codesandbox.io/s/peaceful-chatelet-hbpmw
I assumed react re-renders whenever it sees changes in VirtualDOM, it clearly re- renders in this scenario.
My question is what is triggering the reconciliation engine so that react figures out the change and re-renders?
One explanation would be the entire DOM re-renders normally and react has a stale copy of the DOM.
But in that case I suppose this should happen
- When next time react renders it should think it has an updated copy and change the color back to black.
React doesn't re-create the whole real-DOM tree, but only updates the properties that have changed in the virtual DOM, which is the whole purpose of using a virtual DOM.
The word "render" is used ambiguously sometimes, but here it means render the virtual DOM, and not render the real DOM.
What you see on the screen is always the real DOM, so if you change the real DOM directly, you see that change immediately, but React is not involved here at all.
If you change the real DOM directly, then React doesn't know anything about that change, and doesn't re-render. The virtual DOM is not changed.
When React re-renders the next time (for any other reason),
React checks if the color has changed in its virtual DOM, but the color in the virtual DOM has not changed, is was black and is still black,
so React does not update the color in the real DOM, but just leaves it untouched as it is right now, which is red.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With