Last active
November 15, 2023 04:40
-
-
Save leonadler/6f14c7554332bd319bc8f931ce596c0b to your computer and use it in GitHub Desktop.
Detect React StrictMode
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { useIsInStrictMode } from './useIsInStrictMode'; | |
| test('detect strict mode', async () => { | |
| function TestComponent() { | |
| const [isInStrictMode, CheckStrictMode] = useIsInStrictMode(); | |
| return ( | |
| <p> | |
| <CheckStrictMode /> | |
| {`Strict mode: ${isInStrictMode ? 'on' : 'off'}`} | |
| </p> | |
| ); | |
| } | |
| const { container } = render( | |
| <> | |
| <a> | |
| <TestComponent /> | |
| </a> | |
| <StrictMode> | |
| <b> | |
| <TestComponent /> | |
| </b> | |
| </StrictMode> | |
| </> | |
| ); | |
| expect(container).toMatchInlineSnapshot(` | |
| <div> | |
| <a> | |
| Strict mode: off | |
| </a> | |
| <b> | |
| Strict mode: on | |
| </b> | |
| </div> | |
| `); | |
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // I want to explicitly state that this is a bad idea; | |
| // but sometimes Reacts double-render causes issues that are hard to debug. | |
| // | |
| // The big downfall of StrictMode is that your unit tests will correctly claim | |
| // "your component works", which it will in production, but might not in development. | |
| function useIsInStrictMode() { | |
| const [isStrictMode, setIsStrictMode] = useState(false); | |
| const renderCount = useRef(0); | |
| const Detector = useRef(() => { | |
| if (++renderCount.current > 1) { | |
| setIsStrictMode(true); | |
| } | |
| return null; | |
| }).current; | |
| return [isStrictMode, Detector] as const; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment