Question About useParams Not Updating After window.history.pushState in Next.js 14.2.12 #70779
-
Hi there! I’m a beginner working with Next.js 14.2.12, and I have a question regarding the useParams hook from next/navigation. I’m trying to log the parameters obtained from useParams, but it doesn't seem to update when I change the URL using window.history.pushState(). Here’s a simplified version of my code:
The Issue: My Question:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
The issue you're encountering is due to how the useParams hook from next/navigation works in Next.js. The useParams hook is designed to work with Next.js's built-in routing system, which relies on the framework's internal mechanisms to detect route changes. When you use the window.history.pushState() method, you're bypassing these mechanisms, so useParams doesn't detect the change. Here's how you can address this issue: Solution: Use Next.js Routing Here's how you can modify your component to use useRouter: // pages/quotation/[step].js
import { useRouter } from 'next/router';
import { useEffect } from 'react';
const MyComponent = () => {
const router = useRouter();
const { step } = router.query;
useEffect(() => {
console.log(['params', step]);
}, [step]);
const someButton = () => {
// Use Next.js router to change the URL
const newStep = 2; // Example new step value
router.push(`/quotation/${newStep}`);
};
return (
<div>
<button onClick={someButton}>Change Step</button>
</div>
);
};
export default MyComponent; |
Beta Was this translation helpful? Give feedback.
The issue you're encountering is due to how the useParams hook from next/navigation works in Next.js. The useParams hook is designed to work with Next.js's built-in routing system, which relies on the framework's internal mechanisms to detect route changes. When you use the window.history.pushState() method, you're bypassing these mechanisms, so useParams doesn't detect the change.
Here's how you can address this issue:
Solution: Use Next.js Routing
Instead of using window.history.pushState(), you should use Next.js's built-in routing capabilities, such as the useRouter hook from next/router. This will ensure that your component re-renders with the updated parameters when the URL changes.
H…