Pure React stateless component
A React component's render function is "pure" when it renders the same result given the same props and state. You can use this for a performance boost in some cases.
Under the hood, this wrap the stateless component into a class component implementing shouldComponentUpdate
,
in which it shallowly compares the current props with the next one and returns false if the equalities pass.
Not always. That's why react can't do pure optimisations by default on them.
Example of an unpure stateless component:
const Clock = () => <div>{Date.time()}</div>
An unpure component can also be called inside a stateless component.
- If you don't need perf optimisations.
- If you use react-redux, you can use connect to make the component pure.
npm install --save react-pure-stateless-component
import React, { PropTypes } from 'react';
import createPureStatelessComponent from 'react-pure-stateless-component';
export default createPureStatelessComponent({
displayName: 'MyStatelessComponent',
propTypes: {
i: PropTypes.number,
},
render({ i }) {
return <div>{i}</div>;
}
});
You can also pass a existing stateless component:
import React, { PropTypes } from 'react';
import createPureStatelessComponent from 'react-pure-stateless-component';
const propTypes = { i: PropTypes.number };
const MyStatelessComponent = ({ i }) => {
return <div>{i}</div>;
};
MyStatelessComponent.propTypes = propTypes;
export default createPureStatelessComponent(MyStatelessComponent);