How to load query params on first render next js
- Import the
useEffect
anduseRouter
hooks from thereact
andnext/router
libraries respectively.
import { useEffect } from 'react';
import { useRouter } from 'next/router';
- Inside your functional component, use the
useRouter
hook to access the current route's query parameters.
const YourComponent = () => {
const router = useRouter();
const { query } = router;
- Use the
useEffect
hook to execute code on the first render of the component.
useEffect(() => {
// Your code to handle and use the query parameters goes here
// For example, you can log them to the console
console.log('Query parameters on first render:', query);
}, []);
- Now, when the component is first rendered, the
useEffect
hook will run, and you can access the query parameters from therouter
object.
That's it! The useEffect
hook with an empty dependency array ensures that the code inside it runs only on the first render.