Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to render React components only once on startup?

I've been reading docs about performance but I can't find the answer to my question...

I have a bunch of buttons on my application that will render based on some properties but not state, parent components will never change their properties. Then I have this onKeyDown event handler that will listen for some keys and update another component.

My problem is that when pressing keys and updating this one component, all the other buttons will render too (observed through React dev tools for Chrome). I haven't implemented shouldComponentUpdate(nextProps, nextState) on my buttons, but shouldn't React have this behavior by default? I mean, compare this.props with nextProps and if they are exactly the same, do not call render()?

Am I supposed to do this myself for every component that should only render once on application startup?

EDIT: PureComponent seems solve the problem... But instead of creating a new question, I'm updating this one with a related question:

Why wouldn't the documentation recommend to have all components based on PureComponent by default? What are the arguments against using PureComponent by default instead of the typical Component?

like image 272
rfgamaral Avatar asked Jan 22 '17 20:01

rfgamaral


1 Answers

Pure components should solve your problem because they implement shallow prop and state comparison by default.

Link to the docs.

If your React component's render() function renders the same result given the same props and state, you can use React.PureComponent for a performance boost in some cases.

like image 165
Michał Pietraszko Avatar answered Oct 18 '22 05:10

Michał Pietraszko