Next.js call function in app.js from component
In order to call a function that is defined in app.js
from a component in Next.js, you will need to do the following:
Import the function in the component that you want to call it from. You can do this at the top of the file, along with your other imports:
import { myFunction } from '../app';
Once the function is imported, you can call it within your component just as you would call any other function:
function MyComponent() {
const handleClick = () => {
myFunction();
}
return (
<button onClick={handleClick}>Click me</button>
);
}
To make sure that your app.js file is included in the bundle that gets sent to the browser, you'll need to include it in the next.config.js
file, under pages
field.
module.exports = {
pages: [
'pages/index.js',
'app.js'
],
}
It is important to note that in Next.js, the app.js
file is used as the "entry point" for the application and contains the top-level App
component that wraps all of the other pages in your application. So, if the function is only going to be called from within this component, you might consider placing it within the app.js
file and wrapping the function in a useEffect
or useCallback
to optimise the performance.