React onclick function log executes when the same state is set after updating the set previously

import React from "react"
import { useState } from "react"

export default function App() {
  const [count, setCount] = useState({ c: 0 })
  console.log(new Date().toString())
  console.log(`Object output ${count.c}`)

  return (
    <div>
      <p>{new Date().toString()}</p>
      {console.log(new Date().toString())};
      <br />
      <p>You clicked Object counter {count.c} times</p>
      <button onClick={() => setCount({ ...count, c: count.c + 1 })}>
        Click me
      </button>
      <p>You clicked Object counter {count.c} times</p>
      <button onClick={() => setCount(count)}>Click me</button>
    </div>
  )
}

In the above React code after updating the count by clicking the first button executes log and re-renders but immediately after that clicking on second button for the first time executes the console logs in the function but do not re-render the component as the date value remains the same for this event and further click on the second button do not execute this log can anyone explain why?

Console-logs-screenshot

138 thoughts on “React onclick function log executes when the same state is set after updating the set previously”

Leave a Comment