Difference between "replace" and "update" turbo streams?

Hello friends,

The turbo handbook enumerates various turbo stream actions - but two of them seem very similar: “replace” and “update”. It is not altogether clear to me what the differences between the two are.


<turbo-stream action="replace" target="message_1">
  <template>
    <div id="message_1">
      This div will replace the existing element with the DOM ID "message_1".
    </div>
  </template>
</turbo-stream>

<turbo-stream action="update" target="unread_count">
  <template>
    <!-- The contents of this template will replace the
    contents of the element with ID "unread_count". -->
    1
  </template>
</turbo-stream>

Looks like both kinda do the same thing: when would you use one over the other, and what are the differences between the two?

Any pointers much appreciated. chrs

I don’t know the specifics of how this is implemented in Turbo, but in the DOM, this could be the difference between innerHTML and outerHTML. When you update something, you replace its contents, and any handlers bound to the container would be retained in the browser. When you replace it, you would completely remove the container and then insert a new container into the DOM. If there were handlers bound to the container, they would need to be rebuilt.

Walter

This is the code that implements each -

  replace() {
    this.targetElements.forEach((e => e.replaceWith(this.templateContent)));
  },
  update() {
    this.targetElements.forEach((e => {
      e.innerHTML = "";
      e.append(this.templateContent);
    }));

thx @defsdoor @walterdavis i’ve put in a PR to clarify this in the docs. I hope it is useful and helps the community.