Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declare a functional component as "pure"

Tags:

reactjs

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>   } } 
like image 490
ᅙᄉᅙ Avatar asked Apr 18 '17 11:04

ᅙᄉᅙ


People also ask

Can we use pure component in functional component?

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.

How do you declare a functional component?

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.

How do you create a pure component in React native?

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.

How do you render a functional component in React?

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.


2 Answers

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> }) 
like image 113
ᅙᄉᅙ Avatar answered Oct 11 '22 15:10

ᅙᄉᅙ


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) 
like image 37
CodinCat Avatar answered Oct 11 '22 13:10

CodinCat