Why Native DOM event always reset React Component state

I know that the Synthetic Event, instead of the native dom event, should be the way to deal with interaction in React App, but I wonder why the behavior is so bizarre. When the React Event works well, and the dom event always reset the state to initial state.

import React, { useState, useEffect } from "react";
import "./style.css";

export default function App() {
  const [num, setNum] = useState(0);
  function clickMe() {
    setNum(num + 1);
  }
  useEffect(() => {
    document.getElementById("app_btn").addEventListener("click", clickMe);
    return () =>
      document.getElementById("app_btn").removeEventListener("click", clickMe);
  }, []);
  return (
    <div>
      <h1>Hello StackBlitz!</h1>
      <div>App {num}</div>
      <button id="app_btn">DOM click</button> <br />
      <button onClick={clickMe}>React Click</button>
    </div>
  );
}

The full project can be opened here https://stackblitz.com/edit/react-wqrmcu?file=src/App.js

51 thoughts on “Why Native DOM event always reset React Component state”

  1. 690499 644389Admiring the time and energy you put into your weblog and in depth details you offer. Its excellent to come across a blog every once in a although that isnt the same old rehashed material. Great read! Ive bookmarked your web site and Im adding your RSS feeds to my Google account. 54979

    Reply