Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Suppress invalid hook call warning for react 18 #3564

Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
25 changes: 23 additions & 2 deletions packages/styled-components/src/utils/checkDynamicCreation.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,16 +10,34 @@ export const checkDynamicCreation = (displayName: string, componentId?: string)
const parsedIdString = componentId ? ` with the id of "${componentId}"` : '';
const message =
`The component ${displayName}${parsedIdString} has been created dynamically.\n` +
'You may see this warning because you\'ve called styled inside another component.\n' +
"You may see this warning because you've called styled inside another component.\n" +
'To resolve this only create new StyledComponents outside of any render method and function component.';

// If a hook is called outside of a component:
// React 17 and earlier throw an error
// React 18 and above use console.error

const originalConsoleError = console.error // eslint-disable-line no-console
try {
let didNotCallInvalidHook = true
/* $FlowIgnore[cannot-write] */
console.error = (consoleErrorMessage, ...consoleErrorArgs) => { // eslint-disable-line no-console
// The error here is expected, since we're expecting anything that uses `checkDynamicCreation` to
// be called outside of a React component.
if (invalidHookCallRe.test(consoleErrorMessage)) {
didNotCallInvalidHook = false
// This shouldn't happen, but resets `warningSeen` if we had this error happen intermittently
seen.delete(message);
} else {
originalConsoleError(consoleErrorMessage, ...consoleErrorArgs);
}
}
// We purposefully call `useRef` outside of a component and expect it to throw
// If it doesn't, then we're inside another component.
// eslint-disable-next-line react-hooks/rules-of-hooks
useRef();

if (!seen.has(message)) {
if (didNotCallInvalidHook && !seen.has(message)) {
// eslint-disable-next-line no-console
console.warn(message);
seen.add(message);
Expand All @@ -31,6 +49,9 @@ export const checkDynamicCreation = (displayName: string, componentId?: string)
// This shouldn't happen, but resets `warningSeen` if we had this error happen intermittently
seen.delete(message);
}
} finally {
/* $FlowIgnore[cannot-write] */
console.error = originalConsoleError; // eslint-disable-line no-console
}
}
};