Compatibility with React.memo (React 16.6)
See original GitHub issueI guess this is a mix between a bug report and a feature request.
Description:
React 16.6 introduces functional component memoization with React.memo.
Components wrapped in the React.memo
HOC will behave similar to components that extend React.PureComponent
or implement a custom shouldComponentUpdate
method, to only re-render when its props change.
If a React.memo
-ed component is used as a base for a new styled component (e.g. by using styled(MemoizedComponent)
), this results in an error:
Error: Cannot create styled-component for component: [object Object].
The “original” component seems to be available in the type
property of the memoized component, so using styled(MemoizedComponent.type)
works, but will presumably circumvent the desired memoization behaviour.
Example:
import React from "react";
import ReactDOM from "react-dom";
import styled from "styled-components";
const Button = ({ children, ...props }) => (
<button {...props}>{children}</button>
);
const MemoButton = React.memo(Button);
// This will crash!
// const StyledMemoButton = styled(MemoButton)`
// color: red;
// `;
// This works
const StyledMemoButton = styled(MemoButton.type)`
color: red;
`;
Reproduction:
https://codesandbox.io/s/n40noyo040
Expected behaviour:
I think especially for presentational components that styled components often are, memoization behaviour could be beneficial, so it would be nice for this to work out of the box. If that’s not a desirable course of action or until it can be implemented, I think documenting that memoized components don’t work with styled-components out of the box and possible ways to mitigate this (e.g. using .type
) would be nice.
Issue Analytics
- State:
- Created 5 years ago
- Reactions:1
- Comments:6 (4 by maintainers)
Top GitHub Comments
Will look into it this weekend
I’m still experiencing this issue in IE 11 (working in all other browsers), I’ve updated react and react-dom 16.8.4 and updated styled-components to 4.1.4-alpha.5 (latest beta). Can you please check this in IE 11 and confirm?
Adding the
MemoButton.type
fixed the issue for me in IE 11, but seems to defeat the purpose to have to add that.