Redux or MobX
most important rules that I can think of:
- react/jsx-no-bind (it gonna bost performance to another level)
- react/prefer-stateless-function (for performance)
- eact/no-multi-comp
- react/prop-types (maybe, with typescript doesn't make much sense I guess)
- react/jsx-handler-names
- react/destructuring-assignment
- react/forbid-component-props (maybe)
- react/jsx-filename-extension (maybe)
more rules:
https://github.com/yannickcr/eslint-plugin-react/tree/master/docs/rules
this'll be optimize performance, there's might be an eslint rule for this
bad:
class myComponent {
computeObject() {
retrun {
a: 1,
b: 2,
}; // it'll re-create a new object each time
}
render() {
const myArray = [1,2,3,4,5,6,7,8]; // it'll re-create a new array with a different refrence
const myObject = this.computeObject();
retrun (
<MyOtherComponent
myArray={myArray}
myObject={myObject}
/>
);
}
}
good:
class myComponent {
computeObject() {
if (!this.myObject) {
this.myObject = {
a: 1,
b: 2,
};
}
return this.myObject;
}
render() {
const myObject = this.computeObject();
retrun (
<MyOtherComponent
myArray={myArray}
myObject={myObject}
/>
);
}
}
const myArray = [1,2,3,4,5,6,7,8];
somthing like https://github.com/alexreardon/memoize-one can become handy.
decorations can become very handy in some cases, for example:
import {
get,
put,
} from '../api';
@get('users/1')
@get('users/2', {
name: 'user2', // prop name
})
@put()
class myComponent {
handleEditUser(data) {
this.props.put('users/1', data);
}
render() {
if (this.props.data.loading || this.props.user2.loading) {
retrun (
<Loading/>
);
}
const {
data: {
user,
},
user2: {
secondUser: user,
},
} = this.props;
retrun (
<ShowUsers
firstUser={user}
secondUser={secondUser}
/>
);
}
}
I think decorations can be useful for api call or even forms (e.g. @form({ fields, options })
)
@tobscure in most cases yes, in that particular example I just wanted to show it's better to minimize computations in
render()
as much as possible and avoid recreating objects and arrays props insiderender()
to prevent re-rendering:bad:
good:
I might be wrong, but as I can recall when React want to re-render a component (e.g. when its parent props has been changed), React will do deep equal check (for normal components) to check if props has been changed only if the props reference has been changed, I guess it's something like this:
in second example we'll avoid a
areDeepEqual()
(which affects performance, specially in case of a component with lot's of props) becausememoizedColors
return same array each time, henceoldColors !== newColors --> false
on the other hand if we pass a new reference to a pure component it'll results a re-render, because pure components are only do a shallow comparison (it will do not call any
areDeepEqual()
on objects and arrays, only a simple===
), so it will gonna results re-rendering.