66

How to signal to React that a functional component is "pure", as an equivalent of React.PureComponent for component classes?

function C(props) { 
  return <var>{props.n}</var> 
}

without making it a class

class C extends React.PureComponent {
  render() {
     return <var>{this.props.n}</var>
  }
}
0

4 Answers 4

108
+300

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>
})
2
  • Should we add this to all pure components? Or if we follow a container view pattern should we add memo to all views?
    – coder
    Commented May 8, 2022 at 4:25
  • 1
    @coder Naively, yes, but in practice, I'm not so sure. It does have a performance cost: diffing props, and of course a performance benefit: avoiding re-renders when the props didn't change. Your best bet is to benchmark the app with and without.
    – P Varga
    Commented May 11, 2022 at 3:35
16

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);
    
1
  • 3
    Could you specify recompose benefits over native react solution? Commented Sep 28, 2022 at 10:19
13

To @Shubham and @Andrew:
No, functional components are not PureComponents. Functional components will always get re-render if the parent component re-renders. A PureComponent contains a default shouldComponentUpdate() and I think that's what OP wants.


You can use pure provided by recompose to wrap and optimize your functional components:

import pure from 'recompose/pure'

const YourFunctionalComponent = (props) => {
  ...
}

export default pure(YourFunctionalComponent)
12

In addition to CodinCat answer.

The author of the library, recomponse, wrote a note on 25th Oct of 2018, where he stated, that what he tried to solve by the library was solved by the React Team through introducing hooks. Not only that, React team added optimization feature like React.memo(), which was named as React.pure() earlier. So, it's time to use React.memo(). Read Official Docs about it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.