Jason Peng
Jason Peng

Reputation: 396

Should I manipulate DOM directly or using React state/props?

This is the situation:

This component renders many data as a list. If I use React state/props to control the DOM style(add classes or modify some attributes), React will always run the render() function when user reacts with the list, like mouseover, click and etc..

Though React has virtual DOM technology, but I think it is still very inefficient to run render() every time. The documents do not recommend to manipulate DOM directly, but I think it is more efficient. What should I do? Thx.

Upvotes: 0

Views: 2593

Answers (3)

normal snail
normal snail

Reputation: 1

Even tho It seem like react is rerendering a lot. React is still much faster than manipulating the real dom

Upvotes: 0

Shubham Khatri
Shubham Khatri

Reputation: 282160

As far as rerendering in react is concerned, it has been heavily optimised. You may think that the render() function runs on every small manipulation but the thing that is not visibile is that the rerender doesn't occur for the entire DOM rather on only the portion that has changed.

React uses the virtual DOM technology and then it takes out the difference between the current and the virtual dom much like string comparison and then only renders the difference and is thus highly efficient.

So I would recommend you to follow the documentation and not mix DOM manipulation with react.

Upvotes: 1

Seanr707
Seanr707

Reputation: 11

I wouldn't mix writing React with directly manipulating the DOM; do either but not both.

If you are already using React, just use it for what you want. If possible, break the components into as small of pieces as possible; this will help the number renders.

It may be slightly more inefficient to have React re-render too much, but remember that React has been heavily optimized for DOM manipulation.

Upvotes: 1

Related Questions