How do I use WebViewer with React strict mode?

When React Strict Mode is enabled, components will re-render an extra time and useEffect hooks will also be re-run. This is to help you find bugs and memory leaks caused by impure rendering or missing effect cleanups.

When initializing WebViewer in a useEffect, strict mode will cause WebViewer to mount twice which may cause unexpected behaviour.

There are a few options to work around this undesired behaviour.

1. Prevent remounting

The easiest way to prevent this behaviour is to add a check to your useEffect that prevents WebViewer from reinitializing. The easiest way to do so is by setting a flag after the initial render and then exiting the useEffect early if it is set.

This is the recommended approach

JavaScript

1import WebViewer from "@pdftron/webviewer";
2import { useEffect, useRef } from "react";
3
4export default function WebViewerComponent() {
5
6 const ref = useRef(null);
7 const hasMounted = useRef(false);
8
9 useEffect(() => {
10 if (hasMounted.current) {
11 return;
12 }
13 hasMounted.current = true;
14
15 WebViewer({
16 ...
17 }, ref.current)
18 .then((instance) => {
19
20 })
21 }, [])
22
23 return (
24 <div ref={ref} />
25 )
26}

2. Disable strict mode

Another option is to remove strict mode all together. Doing so will stop WebViewer from mounting twice, but you will lose the debugging benefits of having it enabled.

To remove strict mode, delete the <StrictMode> element that wraps your application.

Did you find this helpful?

Trial setup questions?

Ask experts on Discord

Need other help?

Contact Support

Pricing or product questions?

Contact Sales