#how do I force script to run on every render?

1 messages · Page 1 of 1 (latest)

edgy laurel
#

how do I force script to run on every render?

wide thicketBOT
#

Hi @edgy laurel. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

In Next.js, you can use the onReady event handler with the Script component to execute additional code every time the component is mounted. This means the code will run after the script has finished loading and every time the component is re-rendered.

Here's an example of how to use onReady:

import { useRef } from 'react'
import Script from 'next/script'
 
export default function Page() {
  const mapRef = useRef()
 
  return (
    <>
      <div ref={mapRef}></div>
      <Script
        id="google-maps"
        src="<https://maps.googleapis.com/maps/api/js">
        onReady={() => {
          new google.maps.Map(mapRef.current, {
            center: { lat: -34.397, lng: 150.644 },
            zoom: 8,
          })
        }}
      />
    </>
  )
}

In this example, a Google Maps JS embed is re-instantiated every time the component is mounted.

Please note that onReady does not yet work with Server Components and can only be used in Client Components.

For more information, refer to the next/script API reference (https://nextjs.org/docs/pages/api-reference/components/script#onready).

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@edgy laurel kapa.ai is still learning and improving, please let us know how it did by reacting below

edgy laurel
#

I want to run the external script defined in "src" on every render

#

@wide thicket I want to run the external script defined in "src" on every render

wide thicketBOT
#

Let me check the knowledge base for you. One moment! :books:

#

To run an external script on every render in Next.js, you can use the Script component from next/script. However, please note that Next.js optimizes the loading of scripts to ensure they only load once, even if a user navigates between multiple pages. This is to minimize any unnecessary impact on performance.

If you want to execute additional code every time the component is mounted, you can use the onReady event handler. This will execute the code after the script has finished loading and every time the component is re-rendered.

Here's an example:

import Script from 'next/script'
 
export default function Page() {
  return (
    <>
      <Script
        src="<https://example.com/script.js">
        onReady={() => {
          console.log('Script has loaded')
        }}
      />
    </>
  )
}

In this example, the console will log 'Script has loaded' every time the component is re-rendered.

For more information, refer to the next/script API reference (https://nextjs.org/docs/pages/api-reference/components/script#onready).

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: