0

Using Next.js, I can get the context value in header.js file without a problem but it returns undefined in _app.js

Here is my code.

useLang.js

import { createContext, useContext, useState } from 'react'

const LangContext = createContext()

export const LangProvider = ({ children }) => {
  const [lang, setLang] = useState('en')
  const switchLang = (selected) => setLang(selected)

  return (
    <LangContext.Provider value={{ lang, switchLang }}>
      {children} 
    </LangContext.Provider>
  )
}

export const useLang = () => useContext(LangContext)

_app.js

import { LangProvider, useLang } from '../hooks/useLang'

export default function MyApp(props) {
  const { Component, pageProps } = props

  const contexts = useLang()
  console.log(contexts) // ------> undefined. why ???

  return (
    <LangProvider>
      <Component {...pageProps} />
    </LangProvider>
  )
}

header.js

import { useLang } from '../hooks/useLang'

export default function Header() {
  const { lang } = useLang() // ------> works fine here!

  return <> {lang} </>
}

I've looked at the Next.js documentation, but nowhere does it mention that you cannot use the state or context in _app.js. Any help would be appreciated.

bubbleChaser
  • 755
  • 1
  • 8
  • 21

1 Answers1

1

Yes, you can not get the value of context on _app.js because on top _app.js mustn't children of LangProvider. You just only can use context's value on children component of LangProvider container.

cuongdevjs
  • 711
  • 6
  • 15