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> } }
PureComponent since by definition, they are not classes. If you want React to treat a functional component as a pure component, you'll have to convert the functional component to a class component that extends React.
To answer, it is as simple as creating a function returning an HTML-like syntax. import React from 'react'; function Counter({n}) { return ( <div>{n}</div> ); } export default Counter; Now let's see what happened in the code above. Counter is a function that transforms a number into HTML.
Components can be termed as pure if they return same output for same input values at any point of time. If state or props references new object, PureComponent will re-render every time. We can use forceUpdate to manually re-render even if shouldComponentUpdate fails.
We can create a functional component to React by writing a JavaScript function. These functions may or may not receive data as parameters. In the functional Components, the return value is the JSX code to render to the DOM tree. Example: Program to demonstrate the creation of functional components.
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> })
To @Shubham and @Andrew:
No, functional components are not PureComponent
s. 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)
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