Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does React perform a deep compare or a shallow compare in render method?

Tags:

reactjs

React Document says

React.PureComponent's shouldComponentUpdate() only shallowly compares the objects.

Does it mean the Component will do a deep compare unless we make it a PureComponent ?

like image 331
Etherealm Avatar asked Jan 22 '18 10:01

Etherealm


People also ask

Does React Compare deep?

No, by default Component will re-render even if its props stay the same (by doing no compare at all), unless you decide to implement your own shouldComponentUpdate . From docs: render() will not be invoked if shouldComponentUpdate() returns false.

Does React compare shallow?

React does a shallow comparison. If you use an object or an array that you mutate, React will think nothing changed. Because objects are compared by reference.

What is shallow and deep comparison in React?

Shallow compare works by checking if two values are equal in case of primitive types like string, numbers and in case of object it just checks the reference. So if you shallow compare a deep nested object it will just check the reference not the values inside that object.

What is actually rendered by React render method?

React renders HTML to the web page by using a function called render(). The purpose of the function is to display the specified HTML code inside the specified HTML element. In the render() method, we can read props and state and return our JSX code to the root component of our app.


1 Answers

No, by default Component will re-render even if its props stay the same (by doing no compare at all), unless you decide to implement your own shouldComponentUpdate.

From docs:

render() will not be invoked if shouldComponentUpdate() returns false.

and then:

shouldComponentUpdate() is invoked before rendering when new props or state are being received. Defaults to true.

like image 159
pwolaq Avatar answered Oct 19 '22 08:10

pwolaq