Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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}

like image 682
Ryc Avatar asked Oct 25 '18 21:10

Ryc


People also ask

How do you use React memo with Connect?

memo within many HOC would be to be the closest to the component itself : the goal of React. memo is to check if all the new props received by the component are the same as the last props. If any HOC transforms or adds any props to the component - which connect does by mapping the Redux store to the props, React.

How do I connect Redux With React?

The connect() function connects a React component to a Redux store. It provides its connected component with the pieces of the data it needs from the store, and the functions it can use to dispatch actions to the store.

Can I use Redux connect with React hooks?

React Redux recently released version 7.1, which includes long awaited support for React Hooks. This means that you can now ditch the connect higher-order component and use Redux with Hooks in your function components.

What is the difference between useMemo and React memo?

In useMemo it remembers the value returned between renders, and in React. memo it remembers the react component between renders. As you can see here React. memo is a higher-order component that accepts a react component and memoizes it depending on your props.


1 Answers

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(...)())

like image 171
Bhojendra Rauniyar Avatar answered Sep 30 '22 21:09

Bhojendra Rauniyar