Skip to content

Commit

Permalink
feat: check dynamic creation in React 18
Browse files Browse the repository at this point in the history
  • Loading branch information
lynndylanhurley committed Aug 21, 2021
1 parent 0fe61fd commit e2ea6ec
Showing 1 changed file with 21 additions and 2 deletions.
23 changes: 21 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,33 @@ 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
try {
let didNotCallInvalidHook = true
console.error = (consoleErrorMessage, ...consoleErrorArgs) => {
// 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 +48,8 @@ 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 {
console.error = originalConsoleError;
}
}
};

0 comments on commit e2ea6ec

Please sign in to comment.