Rendering in react.

Understanding how variables works for the front end:

When we edit a variable in js, it doesn't reflect on the html document or in the frontend because the page/component does not re-render to reflect the change in the html page.

Example:


function App() {
  let count = 0;

  function incrementCount() {
    count = count + 1;
  }

  return (
    <>
      <h1>your count is {count}</h1>
      <button onClick={incrementCount} 
      style = {{ backgroundColor:'black', color:'yellow' }} >ClickME</button>
    </>
  );
}
export default App;

Regardless of how many times you click. The total will be zero. Because react does not re-render the component to display the new count.

output:

Nevertheless, if you employ console.log. It will display the most recent count value for the count variable as shown below:


function App() {
  let count = 0;

  function incrementCount() {
    count = count + 1;
    console.log(count);
  }

  return (
    <>
      <h1>your count is {count}</h1>
      <button
        onClick={incrementCount}
        style={{ backgroundColor: "black", color: "yellow" }}
      >
        ClickME
      </button>
    </>
  );
}
export default App;

Reason:

Data is not re-rendered into the screen as functional components are stateless components. Stateless components are unable to change their state while the application is executing, hence they cannot be redrew while the application is active. The revised value of the data will be returned if we console.log the count right away after pushing the button using the syntax "console.log(count)", but the stateless nature of the component prohibits it from rendering again, so we won't be able to see the new number on the screen.

useState hook

By default, react will not maintain track of these variables in order to re-render the component. To make react re-render, use the useState hook, as seen below.

import {useState} from "react"
function App() {
  const [count,setCount] = useState(0)

  function incrementCount() {
    setCount(count=>count+1)
  }

  return (
    <>
      <h1>your count is {count}</h1>
      <button onClick={incrementCount} style = {{backgroundColor:'black',color:'yellow'}}>Click ME</button>
    </>
  );
}
export default App;

When the count changes, react will re-render the component that uses this count state variable, and it will appear on the webpage.