Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent multiple renders on React PDF?

My Electron + React App uses ReactPDF to render documents, however if I change some variables and set state that have nothing to do with it, the document will re-render, which is very annoying. I'm rendering as following:

 <Document

 onLoadSuccess={({ numPages }) => setNumPages(numPages)}

 noData={<Loader />}

 file={{ data }}

 options={docOptions}

 >
      {Array.from(new Array(numPages), (el, idx) => (
        <div
          className="border"
          key={`page_container_${idx + 1}`}
        >
          <Page
            key={`page_${idx + 1}`}
            scale={currentZoom}
            pageNumber={idx + 1}
            customTextRenderer={makeTextRenderer(searchText)}
            onGetAnnotationsSuccess={(a) => loadFileAnnotations(a)}`

https://github.com/wojtekmaj/react-pdf/issues/656

like image 427
Pedro Silveira Avatar asked Sep 05 '25 03:09

Pedro Silveira


1 Answers

Please use React.memo to stop re-rendering

const PdfRender = React.memo(({ invoiceData }: any) => {
  return (
    invoiceData?.pdfUrl && (
      <Document
        renderMode="svg"
        file={{
          url: invoiceData?.pdfUrl,
        }}
      >
        <Page pageNumber={1} />
      </Document>
    )
  );
});

const Invoice = () => {
    const [invoiceData, setInvoiceData] = useState({
        pdfUrl: "",
    });
     useEffect(()=>{
         // set pdfurl in invoice data here first time
     },[]);
     return (<div>
        <PdfRender invoiceData={invoiceData} />
     </div>);
}


like image 178
Sourav Singh Avatar answered Sep 07 '25 21:09

Sourav Singh