Declare a functional component as "pure"

As of React 16.6.0, memo has been added, so the answer is now:

const C = React.memo(props => {
  return <var>{props.n}</var>
})

Based on the concept of purity in functional programming paradigms, a function is pure if:

  • Its return value is only determined by its input values
  • Its return value is always the same for the same input values

There seem two ways to do it for React functional components:

  1. Using memo from react:

    import React, { memo } from 'react';
    
    const Component = (props) {
      return (
        // Component code
      )
    }
    
    // Wrap component using "memo" HOC
    export default memo(Component);
    
  2. Using pure from recompose:

    import React from 'react';
    import { pure } from 'recompose';
    
    const Component = (props) {
      return (
        // Component code
      )
    }
    
    // Wrap component using "pure" HOC
    export default pure(Component);
    

Tags:

Reactjs