Search code examples
reactjsreact-context

How to render a component that use usecontext


i have a element that said

<p>{theme ? : "true" , "false"}</p>

theme = useContext(themeContext) in consol it said true and i can change it with a button

in console theme value change to true and false the but p element wont render or update

 // rootlayout

 export default function RootLayout({ children }) {
 return (
 <html lang="en">
  <body>
    <ThemeProvider>
      <Navbar />
      {children}
      <Footbar />
    </ThemeProvider>
  </body>
</html>
 );
 }


 //createcontext 
"use client";
 import { createContext, useState } from "react";

  export const ThemeContext = createContext(true);

 export default function ThemeProvider({ children }) {
  const [ubah, setUbah] = useState(true);
 return (
 <ThemeContext.Provider value={{ ubah, setUbah }}>
  {children}
</ThemeContext.Provider>
);
}
      // element i want to change 
   export default function Switchbg(props) {
    let { ubah, setUbah } = useContext(ThemeContext);
    console.log(ubah);

  return (
  <>
  <p>{ubah ? "true" : "false"}</p>
  </>)

Solution

  • If you can give us a simple reproduction of your issue, we'd be able to assist better. That said,

    When using a context provider like so,

    function RootProvider({children}) {
      ...
      return <MyContext.Provider value={{}}>{children}</MyContext.Provider>
    }
    

    You need to make sure that the consumer of the context is a child of the provider.

    ...
      return <RootProvider><MyComponentThatUsesContext /></RootProvider>
    ...
    
    function MyComponentThatUsesContext() {
      const ctx = useContext(MyContext)
      return <>foo</>
    }
    

    I also notice that you're using SSR or nextjs... Server side components are not rendered on the client (hence the naming). You would not have access to client context server side. Check if you are mixing components as well.