react-pure-stateless-component

0.3.0 • Public • Published

react-pure-stateless-component NPM version

Pure React stateless component

Dependency Status

Why this package ?

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.

Stateless components are not pure ?

Not always. That's why react can't do pure optimisations by default on them.

Exemple of a unpure stateless component:

const Clock = () => <div>{Date.time()}</div>

An unpure component can also be called inside a stateless component.

When not to use ?

  • If you don't need perf optimisations.
  • If you use react-redux, you can use connect to make the component pure.

Install

npm install --save react-pure-stateless-component

How to use

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);

Similar libraries

Package Sidebar

Install

npm i react-pure-stateless-component

Weekly Downloads

1

Version

0.3.0

License

ISC

Last publish

Collaborators

  • churpeau