You can easily render and re-render a page in React but that’s not a recommended way of changing the DOM.
Similar read: How states work in React?
In that post I have a live demo of time changing every second. In this current post, let’s go through the bits and pieces of the useState function.
Change your app.js and index.js
If you’re adding the code in local files and not in a online code editor, you need to import state hook (useState) to add state to App component.
index.js
So your index.js file is going to be same other than removing additional variables that we added in re-rendering post.
import ReactDOM from 'react-dom'
import App from './App'
ReactDOM.render(,
document.getElementById('root'))
App.js
Let’s create App.js step by step. First of all, it will have the state hook imported.
import React, { useState } from 'react'
...
Now, we need to add state to the component and render it as well as initialize it with a value.
import React, { useState } from "react";
const App = () => {
const [wait, showWaitTime] = useState(0);
};
export default App;
The App function above will call another function when it runs and adds state to the component. Also, it renders it with an initial value of 0.
The same function will return an array that has two items, which values will be stored in wait and showWaitTime. That way of storing values is called destructuring.
So, overall, the initial value we pass in useState will be stored in wait as well as the same value will be rendered initially.
The showWaitTime will be used to modify the state using the assigned function.
Time to finally render something
Let’s add the setTimeout function to render the component and change it every second.
import React, { useState } from "react";
const App = () => {
const [wait, showWaitTime] = useState(0);
setTimeout(() => showWaitTime(wait + 1), 1000);
return You've been waiting since {wait} seconds!;
};
export default App;
When you call showWaitTime function for the first time to modify the state, React re-renders the component and executes the component function and sets the value to 0. But when it gets called for the second time, it calls useState function and returns a value by adding 1.
Every time the function body gets executed, it calls setTimeout, which calls the showWaitTime and the loop continues.
Every time the showWaitTime modifies the state it makes the component to re-render.
components examples props render states