For the complete documentation index, see llms.txt. This page is also available as Markdown.

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

import WebViewer from "@pdftron/webviewer";
import { useEffect, useRef } from "react";

export default function WebViewerComponent() {

  const ref = useRef(null);
  const hasMounted = useRef(false);

  useEffect(() => {
    if (hasMounted.current) {
      return;
    }
    hasMounted.current = true;

    WebViewer({
      ...
    }, ref.current)
      .then((instance) => {

      })
  }, [])

  return (
    <div ref={ref} />
  )
}

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.

Last updated

Was this helpful?