Skip to content

Instantly share code, notes, and snippets.

@leonadler
Last active November 15, 2023 04:40
Show Gist options
  • Select an option

  • Save leonadler/6f14c7554332bd319bc8f931ce596c0b to your computer and use it in GitHub Desktop.

Select an option

Save leonadler/6f14c7554332bd319bc8f931ce596c0b to your computer and use it in GitHub Desktop.
Detect React StrictMode
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>
`);
});
// 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