DEV Community

Sai Tanmayee Chervi
Sai Tanmayee Chervi

Posted on • Updated on

Can we call root.render() inside setInterval()?

Why doesn't the below code work?

const root = ReactDOM.createRoot(document.getElementById('root'));

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

setInterval( root.render(<Clock />), 1000);
Enter fullscreen mode Exit fullscreen mode

But why does wrapping the root.render() in a tick method like below work?

const root = ReactDOM.createRoot(document.getElementById('root'));

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

function tick() {
  root.render(<Clock date={new Date()} />);
}

setInterval(tick, 1000);
Enter fullscreen mode Exit fullscreen mode

Forgive me! I'm a beginner :)

Top comments (0)