Search code examples
reactjstypescriptnext.jsreact-pdf

react-pdf throwing Rendered more hooks than during the previous render


I'm implementing react-pdf to show a pdf within a web view. The react app works with Typescript and Next if that helps in any way.

So far, this is my code

const MyPage: NextPage = () => {
// some code here
  const [numPages, setNumPages] = useState(null);
  const onDocumentLoadSuccess = (numPages:any) =>  {
      setNumPages(numPages);
    }
  return (
    <>
          <div className="white-background">
            <hr />
            <div className="pdf-container">
              <Document
                file={data?.pdf}
                options={{ workerSrc: "/pdf.worker.js" }}
                onLoadSuccess={onDocumentLoadSuccess}
              >
                {Array.from(new Array(numPages), (el, index) => (
                  <Page key={`page_${index + 1}`} pageNumber={index + 1} />
                ))}
              </Document>
              <p>
                Page {pageNumber} of {numPages}
              </p>
            </div>
            
          <hr/>
          </div>

   </>

As far as I'm concerned, I used the component the same way as the documentation, but it is throwing this error ->

Uncaught Error: Rendered more hooks than during the previous render.

pointing to const [numPages, setNumPages] = useState(null); especifically to useState(null)

I strongly believe that the problem comes from calling onLoadSuccess={onDocumentLoadSuccess} as the function is calling the reference to the hook and whenever it returns it loads an extra hook within page, which throws the error.

The problem then is that onLoadSuccess is expecting a reference and not a function

I already tried passing with parenthesis () but it throws an error. So no clue so far.

Any idea on how to solve it?


Solution

  • The problem was that I was placing

    const [numPages, setNumPages] = useState(null);

    after a conditional in my Function Component. I placed it at the top and the problem was fixed.