Skip to content
This repository has been archived by the owner on Dec 17, 2019. It is now read-only.

christophehurpeau/react-pure-stateless-component

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

22 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

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.

Example of an 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