React Context is behaving differently in Next.js
Unanswered
Mugger Crocodile posted this in #help-forum
Mugger CrocodileOP
Hi there!
I'm new to Next.js and trying to graps the concepts of Hooks in Next. I know that these hooks don't function different in Next but they sometimes behave differently.
So in here im creating a Context in Providers.jsx and and proving {name} so that i can get this variable in any of nested components.
//Provider.jsx (below is code for Provider Context)
//layout.jsx (in here i implemented Provider)
//TextBlock.jsx (here i tried to use the context value but its not working)
ERROR
I'm new to Next.js and trying to graps the concepts of Hooks in Next. I know that these hooks don't function different in Next but they sometimes behave differently.
So in here im creating a Context in Providers.jsx and and proving {name} so that i can get this variable in any of nested components.
//Provider.jsx (below is code for Provider Context)
"use client"
import { createContext, useContext } from "react";
const UserContext = createContext()
export const Provider = ({children}) => {
const user = "Abdul"
const contextData = {
user,
}
return(
<UserContext.Provider value={contextData}>
{children}
</UserContext.Provider>
)
}
//Custom Hook
export const useContextProvider = ()=> {return useContext(UserContext)}
export default UserContext;//layout.jsx (in here i implemented Provider)
import { Inter } from "next/font/google";
import "./globals.css";
const inter = Inter({ subsets: ["latin"] });
import { Provider } from "@/utils/Provider";
export const metadata = {
title: "Create Next App",
description: "Generated by create next app",
};
export default function RootLayout({ children }) {
return (
<html lang="en">
<Provider>
<body className={inter.className}>{children}</body>
</Provider>
</html>
);
}//TextBlock.jsx (here i tried to use the context value but its not working)
import { useContextProvider } from "./utils/Provider";
const TextBlock = () => {
const { name } = useContextProvider();
return (
<div>{name}</div>
)
}
export default TextBlockERROR
Unhandled Runtime Error
Error: (0 , _utils_Provider__WEBPACK_IMPORTED_MODULE_1__.useContextProvider) is not a function2 Replies
Ocicat
Hey, can you try to add "use client" at the top in RootLayout? If I remember correctly, it could be it.
Yeah, sorry I didn't remember it quite correct. Check this out:
https://vercel.com/guides/react-context-state-management-nextjs
You would have to create another wrapper component for the providers, there you should add "use client" at the top and then use that in RootLayout.
https://vercel.com/guides/react-context-state-management-nextjs
You would have to create another wrapper component for the providers, there you should add "use client" at the top and then use that in RootLayout.