Skip to content

Feature: Implement lint rule about using node variable in update closure #9111

Description

@levensta

Description

In some cases, a variable within an update may be closed with a node, especially in the context of React. A contrived example:

const [sourceNode, setSourceNode] = useState<LexicalNode | null>(null)
const [editor] = useLexicalComposerContext();

const handleClick() => {
  if (!sourceNode) return;
  editor.update(() => {
    sourceNode.selectEnd();
  });
}

The pitfall of this code is that, despite checking for the presence of the sourceNode, it may be missing from the LexicalState for some reason during an update. The correct pattern would be to check via the isAttached() method

-  if (!sourceNode) return;
+  if (!sourceNode || !sourceNode.isAttached()) return;

or to store the key and check via $getNodeByKey

-const [sourceNode, setSourceNode] = useState<LexicalNode | null>(null)
+const [sourceNodeKey, setSourceNodeKey] = useState<NodeKey>()
const [editor] = useLexicalComposerContext();

const handleClick() => {
+ const sourceNode = $getNodeByKey(sourceNodeKey);
  if (!sourceNode) return;
  editor.update(() => {
    sourceNode.selectEnd();
  });
}

Otherwise, if the node is detached from the state, the exception will be thrown:

Lexical node does not exist in active editor state.
Avoid using the same node references between nested closures from editorState.read/editor.update.

Impact

A lint rule would prevent such potential errors and allow for safer code handling of state. A similar error can occur not only during updating, but also during reading of state

Activity

  1. etrepum commented on Sep 1, 2026

    @etrepum
    Collaborator

    The error message and the suggested lint rule have no relation to one another. Using is instead of === will never prevent that issue. You can only prevent that issue by using isAttached or $getNodeByKey before using a node reference that might not be in the current state.

  2. changed the title [-]Feature: Implement lint rule that checks node comparisons[/-] [+]Feature: Implement lint rule about using node variable in update closure[/+] on Sep 1, 2026
  3. levensta commented on Sep 1, 2026

    @levensta
    ContributorAuthor

    Ah, right. I corrected the description and added an example

  4. etrepum commented on Sep 1, 2026

    @etrepum
    Collaborator

    This one might be hard to implement in a way that doesn't cause a lot of false positives for perfectly acceptable usage, I would recommend updating the documentation and maybe the invariant message first.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementImprovement over existing feature

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions