Rohit Bansal
Rohit Bansal

Reputation: 1049

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?

Upvotes: 12

Views: 7583

Answers (2)

Drew Reese
Drew Reese

Reputation: 202605

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

Upvotes: 3

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

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

export default React.memo(MyFunctionComponent);

Upvotes: 0

Related Questions