Skip to content

React keys are explicitly unoptimized for re-rendering #703

Description

@remcohaszing

Initial checklist

Problem

As can be seen here, React keys are generated using the name, line, column, and node index. This means that:

  • If the type is changed, it will be presented to React as a new node.
  • If a user enters a newline above the node, it will be presented to React as a new node.
  • If a user changes the content above the node to change the node count (i.e. splitting one paragraph into two), it will be presented to React as a new node.

This means the key is explicitly unoptimized for React re-rendering.

Solution

The key should be calculated as the nth instance if that tag name.

I.e. the following markdown:

# Title

This is a paragraph

![image](./image.png)

This is another paragraph

should be represented as:

<h1 key="h1-0" />
<p key="p-0" />
<img key="img-0" />
<p key="p-1" />

This way if a paragraph changes, only that paragraph is changed. If another paragraph is inserted or removed, only all paragraphs that come after the edited paragraph are rerendered.

Alternatives

  1. Don’t specify a key. This is more performant than the current situation, but React will show warnings.
  2. Change the key to just the index. This is the default behaviour if a key is missing, but React won’t show a warning.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions