modifying DigitalReadSerial example

hi i'm taking my first steps here and am currently looking at the DigitalReadSerial example, which works fine. i'm trying to modify the code, so that it only sends serial data out, if the state of the button changes. when monitoring the code below with the Serial Monitor, everything "looks" ok. but if i send the serial data to the host computer, i sometimes get double triggers, when releasing the button (quick jump form 0 to 1 and back). what might be causing this?

byte state = 0;

void setup() {
  Serial.begin(9600);
  pinMode(2, INPUT);
}

void loop() {
  byte data = digitalRead(2);
  //Serial.println(data, DEC);
  
  if(data != state) {
    state = data;
    Serial.println(state, DEC);
  }
  
  //delay(5);  // this makes it work, but why?

}

You need to do some reading on how switches operate. There are metallic contacts and springs inside. When the button is pressed, the contacts bounce microscopic amounts. Each time they make or break contact, the state of the buttons changes.

The delay statement causes the program to ignore state changes for a small amount of time. By the time it begins reading again, the bouncing has stopped.

ok, makes sense.
thanks,
p