class Option extends React.Component { constructor(props) { super(props); this.handleClickOption = this.handleClickOption.bind(this); } handleClickOption() { // some code } render() { return ( <li onClick={this.handleClickOption}>{this.props.option}</li> ); } }
I use eslint-config-airbnb to check the above code and it show me an error msg like Component should be written as a pure function
.
So how to change the above component to pure function?
Thanks for your help.
To create a pure functional component in React, React provides a React. memo() API. Using the React. memo() API, the React functional component can be wrapped as follows to get React Pure Functional Component.
A React component is considered pure if it renders the same output for the same state and props. For this type of class component, React provides the PureComponent base class. Class components that extend the React. PureComponent class are treated as pure components.
What are the functional component and class component in React? Functional component is just a simple javascript function; it accepts the data in the form of props and returns the react element. Whereas the class component will be created using the class keyword, and it extends the React.
Stateless components are those components which don't have any state at all, which means you can't use this. setState inside these components. It is like a normal function with no render method. It has no lifecycle, so it is not possible to use lifecycle methods such as componentDidMount and other hooks.
React 0.14 introduced pure function components.
This should be the preferred option for all stateless components.
function Option({ onClick, option }) { return ( <li onClick={onClick}> {option} </li> ); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With