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}
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.
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.
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.
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.
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(...)())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With