ErrorOracle
javascript

Error: useRouter only works in Client Components. Add the '…

Error message

Error: useRouter only works in Client Components. Add the 'use client' directive.

What broke

The useRouter hook from Next.js is designed to work only in client components. When it's used in a server component, it throws an error indicating that it cannot be executed in that context.

Why it broke

This broke because server components do not have access to client-side features like routing, which is why the useRouter hook is restricted to client components. The framework enforces this separation to ensure proper functionality.

How to fix

To fix this error, you need to ensure that the component using useRouter is a client component. You can do this by adding the 'use client' directive at the top of your component file.

Code fix

'use client';

import { useRouter } from 'next/router';

const MyComponent = () => {
  const router = useRouter();
  // component logic
};

Explained by ErrorOracle

Prevention tip

You can do this by adding the 'use client' directive at the top of your component file.

Was this helpful?

AI-generated explanation. Always verify fixes in your codebase.