Next.js Discord

Discord Forum

useContext() not working in Layout.jsx

Answered
Caribbean Elaenia posted this in #help-forum
Open in Discord
Avatar
Caribbean ElaeniaOP
When I use useContext() inside layout.jsx, it returns me an error: TypeError: reactWEBPACK_IMPORTED_MODULE_4.useContext(...) is undefined.

I'm not sure why's that. Assistance is needed and appreciated!
Image
Image
Answered by Jesse677
This is how I implement it.
// layout.tsx
export default async function Layout({ children }) {
  const user = getUserFromHeaders();

  return (
    <UserStateProvider user={user}>
      {children}
    </UserStateProvider>
  );
}


// UserStateProvider
"use client";

const UserContext = createContext({} as UserType);
export const useUser = () => useContext(UserContext);

const UserStateProvider = ({ children, user }: PropsType) => {
  return <UserContext.Provider value={user}>{children}</UserContext.Provider>;
};

export default UserStateProvider;
View full answer

12 Replies

Avatar
Caribbean ElaeniaOP
@Jesse677
Avatar
This is how I implement it.
// layout.tsx
export default async function Layout({ children }) {
  const user = getUserFromHeaders();

  return (
    <UserStateProvider user={user}>
      {children}
    </UserStateProvider>
  );
}


// UserStateProvider
"use client";

const UserContext = createContext({} as UserType);
export const useUser = () => useContext(UserContext);

const UserStateProvider = ({ children, user }: PropsType) => {
  return <UserContext.Provider value={user}>{children}</UserContext.Provider>;
};

export default UserStateProvider;
Answer
Avatar
Caribbean ElaeniaOP
I think it's fixed now
💀
I'm not sure how
Oh I know why
This:
export const ThemeContext = createContext();
I have to add an array
export const ThemeContext = createContext({});
Like this
It worked fine now
thanks