Skip to content

Why not to use document.querySelector() #4626

@Josehower

Description

@Josehower

After researching a bit seems to be no official source about why it's not advisable to use document.querySelector() in React.

It seems to be a consensus in the React community about using DOM manipulation methods such as querySelector or getElementById is not the best practice but still in my day to day job as coding teacher I would have an official position on this topic.

Would be possible if you to add some documentation about this, or point me to an authoritative link that I can trust in this regard.

I am looking for an official word from a React team member (or former team member) on why usage of these DOM manipulation methods should be avoided. For example, why are refs recommended (and what can go wrong)? Also, what other types of patterns can be used instead (eg. using state to track variables instead of querying for data in the DOM).

If the project is open to this, I would also be open to creating a pull request to add this official answer to the React documentation.

Thank you in advance for any help.

Good energy 👍👍👍👍

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions