Here’s another post on rendering:
If your application stays same in appearance after the rendering then there is no need to render it again.
Re-rendering is only necessary when your app’s appearance keeps changing constantly or at least more than once.
It’s like creating a counter or a slider in which the visual appearance of the elements needs to be updated again and again. In React, you can do that using states.
You can also update a DOM element without changing its state.
Let’s see how to do that.
//App.js
import React from "react";
const App = ({ wait }) => {
return You're waiting since {wait} seconds!;
};
export default App;
//index.js
import ReactDOM from "react-dom";
import App from "./App";
let wait = 0;
ReactDOM.render( , document.getElementById("root"));
//You're waiting since 0 seconds!
The code above will render the element once but won’t update the number of seconds since you started waiting.
Even if you update the wait variable like this, it will only render the element once!
//index.js
import ReactDOM from "react-dom";
import App from "./App";
let wait = 0;
wait += 1;
ReactDOM.render( , document.getElementById("root"));
//You're waiting since 1 seconds!
It’s not updating the DOM because we’re calling the ReactDOM.render just once!
We’re just updating the DOM once and that’s it. Let’s make a seperate function that will update the DOM each time we call.
Also, at the same time, using setInterval() method, let’s call it after each second and update the DOM.
//index.js
import ReactDOM from "react-dom";
import App from "./App";
let wait = 0;
wait += 1;
const updateDom = () => {
ReactDOM.render( , document.getElementById("root"));
};
setInterval(() => {
updateDom();
wait += 1;
}, 1000);
Calling the ReactDOM.render method again and again and updating the DOM is not recommended. Instead React recommended changing the states.
components DOM examples render setInterval states