Next.js Error: Hooks are not Allowed in Server Components

Updated: April 26, 2023 By: Wolf One comment

The problem

When working with a new version of Next.js (13.x or higher) and using the app directory instead of the traditional pages directory, you might run into the ReactServerComponentsError error. The error messages will look as follows:

You're importing a component that needs [hook name]. It only works in a Client Component but none of its parents are marked with "use client", so they're Server Components by default.

Why does it happen?

The reason that causes the error is that you are trying to use a hook in a component that is treated as a server component by Next.js (all components in the app directory are server components by default). Unfortunately, there are no hooks that are available on server components because server components are executed once per request and do not have state or lifecycle methods. Server components are meant to render HTML on the server and send it to the client without any client-side JavaScript.

The solution

If you want to use hooks in your Next.js application, you need to use client components, which are components that run on the browser and have access to state and lifecycle methods. Client components can use hooks such as useState, useEffect, useRef, useContext, useRouter, and any custom hooks that use them.

To use client components in Next.js, you need to add the use client directive as the first line of your file (before any imports). This will tell Next.js that this is a client component and it can use hooks. Otherwise, Next.js will treat your component as a server component, which cannot use hooks.

Example:

// app/page.tsx
"use client";

import { useState, } from 'react';
import { useRouter } from 'next/navigation';

export default function Home() {
  const [someState, setSomeState] = useState(false);
  const router = useRouter();

  return (
    <></>
  ); 
}

That’s it. Happy coding!

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments