Skip to content

Commit

Permalink
feat: check dynamic creation in React 18
Browse files Browse the repository at this point in the history
[lint]
  • Loading branch information
lynndylanhurley committed Aug 21, 2021
1 parent 0fe61fd commit 2f38179
Showing 1 changed file with 24 additions and 3 deletions.
27 changes: 24 additions & 3 deletions packages/styled-components/src/utils/checkDynamicCreation.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,18 +10,36 @@ 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);
console.warn(message); // eslint-disable-line no-console
seen.add(message);
}
} catch (error) {
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
}
}
};

0 comments on commit 2f38179

Please sign in to comment.