Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to use React.memo in React Native app

I want to use React.memo for optimization in react native.

import React from "react";
import { View, Text } from "react-native";

const Memo = React.memo(function() {
  return (
    <View>
      <Text>Ok</Text>
    </View>
  );
});
class Demo extends React.Component {
  render() {
    return <Memo />;
  }
}

export default Demo;

It gives following error:

TypeError : undefined is not a function (evaluating render(nextProps)). This error is located at : in Demo(at renderApplication.js:34) in RCTView(at View.js:44 )

Can we use React.memo in react native?

like image 851
Rohit Bansal Avatar asked Nov 17 '18 14:11

Rohit Bansal


2 Answers

The "component" you are trying to memoize isn't a correct react component, it isn't being passed any props. The react memo HOC is also only for functional components, use PureComponent for class-based components

You need to ensure you are using the current version of react that introduced the memo HOC, and use it as such:

import React, { Component, memo } from "react";
import { View, Text } from "react-native";

const Demo = props => (
  <View>
    <Text>Ok</Text>
  </View>
);

export default memo(Demo); // memo HOC memoizes return component based on state and props!

React memo

like image 164
Drew Reese Avatar answered Oct 11 '22 02:10

Drew Reese


const MyFunctionComponent = ({text}) => <Text>{text}</Text>;

MyFunctionComponent.displayName = 'HarmlessComponent';
MyFunctionComponent.propTypes = {text: PropTypes.string.isRequired};

export default React.memo(MyFunctionComponent);
like image 32
Moustafa Nour Eldein Avatar answered Oct 11 '22 00:10

Moustafa Nour Eldein