reactjsnext.js13

Context isn't being consumed in Next.js


I'm trying to move my project from react to nextjs and it includes the use of contexts. I wrapped the children in the context provider in layout.tsx file in route that I need (app router). But when I try to consume that context in one of the child components, it doesn't work. It isn't doing anything.

I've made sure that the context creation and the child component and everything is a client side component, it still doesn't work. Could I get some help with this please?

//consuming context
'use client'
import { useState } from "react"
import Image from "next/image"
import api from "../../../interceptors"
import { useRouter } from "next/navigation"
import create_simulation from "../../../public/create_simulation.svg"
import { useUserRoomContext } from "../../../lib/contexts/UserContext"

const CreateInterview = () => {
    const [loading,setLoading]=useState(false)
    const [error,setError]=useState("")
    const [interviewDetails , setInterviewDetails] = useState({
        company_name : "" , 
        job_description : "" , 
        role: "",
        resume: "",
    })
    

    const router = useRouter()
    const {setRoomId, setToken}=useUserRoomContext()
// context
"use client"
import {createContext, useState, useContext} from "react"

const userRoomContext = createContext()
export const useUserRoomContext = () => useContext(userRoomContext)

export const UserRoomProvider = ({children}) =>{

    const [roomId,setRoomId] = useState("")
    const [token,setToken]=useState(null)
    const [reportGenerated,setReportGenerated]=useState(false)

    const value={
        roomId,
        setRoomId,
        token,
        setToken,
        reportGenerated,
        setReportGenerated
    }

    return <userRoomContext.Provider value={value}>
        {children}
    </userRoomContext.Provider>
}

Here is the layout that uses the context provider for its children:

"use client"
import React from 'react'
import { UserRoomProvider } from '@/lib/contexts/UserContext'
import ProtectedRoute from '@/components/protection/ProtectedRoute'

const InterviewLayout = ({children}: Readonly<{children: React.ReactNode}>) => {
    console.log("Interview layout rendered")
    return (

        <UserRoomProvider>
            <ProtectedRoute>{ children }</ProtectedRoute>
        </UserRoomProvider>
      )
    
}

export default InterviewLayout

Solution

  • The implementation looks correct. Here are things you can check upon: