Home > database >  update the UI in React using render method
update the UI in React using render method

Time:10-23

When I read react documentation, they said "the only way to update the UI is to create a new element, and pass it to ReactDOM.render()". due to I have created code like this below.

function Clock() {
 // console.log('clock called'); 

  const element = (
    <div>
      <h1>Hello, world!</h1>
      <h2>It is {new Date().toLocaleTimeString()}.</h2>
    </div>
                  )

  return (
    element
  );
}


ReactDOM.render(
    <Clock/>,
    document.getElementById('root')
  );

//every second call Clock
setInterval(Clock, 1000);

Every second the Clock component is called, so it creates a new element every second. when the Clock component passes to the render method. but the UI is not updated. why? I didn't call the render method every second. because the documentation isn't said: "call the render method every second". I thought when the new element is created, the render method will be called automatically. is my thought ok or not?

In the documentation the code like this below

function Clock(props) {
  return (
    <div>
      <h1>Hello, world!</h1>
      <h2>It is {props.date.toLocaleTimeString()}.</h2>
    </div>
  );
}

function tick() {
  ReactDOM.render(
    <Clock date={new Date()} />,
    document.getElementById('root')
  );
}

setInterval(tick, 1000);

Here they call the render method also every second. but in the documentation, They do not specify to call the render method for each update.

CodePudding user response:

To achieve a dynamic updating for your components, you need to utilize state hooks, like useEffect() and useState.

//import { useState } from 'react';
const { useState, useEffect } = React;

function Clock() {

const time = new Date();
// a hook to maintain the state
 const [ state, setState] = useState();
// a listener to handle changes in the parameters of the array, in our case time
  useEffect(() => {
    setState(time.toLocaleTimeString());
  }, [time])
  
  const element = (
    <div>
      <h1>Hello, world!</h1>
      <h2>It is {state}.</h2>
    </div>
                  )

  return (
    element
  );
}


ReactDOM.render(
    <Clock/>,
    document.getElementById('root')
  );


in the code posted, we use useEffect() hook to respond to any changes in the Date() object. Which was passed in the array after the callback function.

What does this hook do?

it calls useState() hook to update our state variable which I called state, which will be displayed accordingly whenever the time changes.

  • Related