Next.js Discord

Discord Forum

Custom Hooks Error

Unanswered
Blue Picardy Spaniel posted this in #help-forum
Open in Discord
Blue Picardy SpanielOP
I'm trying to make a custom useUser() hook. Here's my code:

app/providers/user.tsx:
"use client";

import { createContext, useState, useEffect } from "react";
import type { User } from "@types";
import { getUser } from "@/lib/api";

interface UserContextType {
  user: User | null;
  setUser: (user: User | null) => void;
}

export const UserContext = createContext<UserContextType | undefined>(undefined);

export default function UserProvider({ children }: { children: React.ReactNode }) {
  const [user, setUser] = useState<User | null>(null);

  useEffect(() => {
    const fetchUser = async () => {
      try {
        const user = await getUser();
        setUser(user);
      } catch (err) {
        console.error(err);
        setUser(null);
      }
    };

    fetchUser();
  }, []);

  return (
    <UserContext.Provider value={{ user, setUser }}>
      {children}
    </UserContext.Provider>
  );
}

app/hooks/useUser.tsx:
import { useContext } from "react";
import { UserContext } from "@/app/providers/user";

const useUser = () => {
  const context = useContext(UserContext);
  return context;
};

export default useUser;

app/layout.tsx:
import UserProvider from "@/app/providers/user";

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <body>
        <UserProvider>
          <Navbar />
          {children}
          <Footer />
        </UserProvider>
      </body>
    </html>
  );
}

Here's my error:
⨯ src\app\hooks\useUser.tsx (5:30) @ UserContextTypeError: (0 , react__WEBPACK_IMPORTED_MODULE_0__.useContext) is not a function
    at useUser (./src/app/hooks/useUser.tsx:11:70)
    at Home (./src/app/page.tsx:17:84)
    at stringify (<anonymous>)
digest: "645657008"
  3 |
  4 | const useUser = () => {
> 5 |   const context = useContext(UserContext);

5 Replies

Velvet ant
I think you need to set the use client directive also for the custom hook
@Velvet ant I think you need to set the `use client` directive also for the custom hook
Blue Picardy SpanielOP
does that mean i can only use the hook in a client file?
Velvet ant
I would say yes
@Velvet ant ~~I would say yes~~
Blue Picardy SpanielOP
how would i go about sharing data to all server components then?
Velvet ant
since the hooks is declare as a client component I think maybe you can use it in server component but not really sure about this, need to try it out. but imo only client component can use context.