Créer un site internet

Best practices snippets

Never Bind in Render

<MyComponent onClick={(id) => this.onClick(id)} />  

Issue :

By binding your event handlers like this, you create brand new functions every time React calls your component’s render.

Solution : bind functions outside of render.


Unnecessary render

<Component {...props}>

Issue :

When container state change : all childs will been rendered (shouldComponentUpdate return true). Unnecessary render.

Solution : pass only necessary props :

<Component necessary={props} >


Never define style in Render

<MyComponent style={ { margin: 0 } } />  

Issue :

New object with margin zero is created on every render.

New object → new reference.

Solution : define constants outside of render :

const myStyle = {margin : 0}; →  outside of render.
<MyComponent style={myStyle} />



React.PureComponent is similar to React.Component. 
The difference between them is that React.Component doesn’t implement shouldComponentUpdate(), but React.PureComponent implements it with a shallow prop and state comparison.

React.PureComponent’s shouldComponentUpdate() only shallowly compares the objects. If these contain complex data structures, it may produce false-negatives for deeper differences.

Only extend PureComponent when you expect to have simple props and state.


React/Redux performance tip - Dan Abramov‏ -

Component separation can make a much bigger difference than manual shouldComponentUpdate() everywhere.


Smarter updates

shouldComponentUpdate give better control over the component’s update cycle by comparing the upcoming props and state from the current ones.

Whatever you do inside shouldComponentUpdate, do it fast. Avoid expensive operations and go directly to shallow comparisons.


js best practices reactjs