How to use React.memo with react-redux connect?

Ryc picture Ryc · Oct 25, 2018 · Viewed 14k times · Source

Does anyone know how to wrap a React component with React.memo when one is using the connect function from react-redux?

For example, how would you modify the following?

let Button = (props: Props) => (
  <button onClick={props.click}>{props.value}</button>
);

Button = connect(
  mapStateToProps,
  mapDispatchToProps
)(Button);

I've tried:

let Button = React.memo((props: Props) => (
  <button onClick={props.click}>{props.value}</button>
));

Button = connect(
  mapStateToProps,
  mapDispatchToProps
)(Button);

However, the function returned by connect expects a component to be passed so it errors with:

Uncaught Error: You must pass a component to the function returned by connect. Instead received {"compare":null}

Answer

Bhojendra Rauniyar picture Bhojendra Rauniyar · Oct 26, 2018

React.memo is nothing but a HOC, so you can just use:

Without memo:

connect(
  mapStateToProps,
  mapDispatchToProps
)(Button);

With memo:

connect(
  mapStateToProps,
  mapDispatchToProps
)(React.memo(Button));

And even wrap to connect: (This should be the solution with connect)

React.memo(
  connect(
    mapStateToProps,
    mapDispatchToProps
  )(Button)
);

Like we do with withRouter: withRouter(connect(...)())