Declare the functional component as "clean"

How do you signal to react that a functional component is "pure" as the equivalent React.PureComponent

for component classes?

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

      

without what the class does

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

      

+6


source to share


2 answers


As of React 16.6.0, a memo was added, so the answer is now:



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

      

+2


source


For @Shubham and @Andrew:
No, functional components are not PureComponent

s. Functional components will always redraw if the parent component is redrawn. PureComponent contains shouldComponentUpdate()

by default and I think this is what the OP wants.




You can use the one pure

provided by Recompose to package and optimize your functional components:

import pure from 'recompose/pure'

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

export default pure(YourFunctionalComponent)

      

+6


source







All Articles