'TypeError: Cannot destructure property 'theme' of '(0 , react__WEBPACK_IMPORTED_MODULE_0__.useContext)(...)' as it is null

I'm working on a Next.js application with TypeScript and I have this error:

"TypeError: Cannot destructure property 'theme' of '(0 , react__WEBPACK_IMPORTED_MODULE_0__.useContext)(...)' as it is null."

This is my _app.tsx file:

import { useContext } from "react"
import { ThemeProvider } from "styled-components"

import ContextProvider from "../context/Context"
import { Context } from "../context/Context"

import GlobalStyle from "../styles/global"

export default function App({ Component, pageProps }) {
  const { theme } = useContext(Context)

  return (
    <ContextProvider>
      <ThemeProvider theme={theme}>
        <GlobalStyle />
        <Component {...pageProps} />
      </ThemeProvider>
    </ContextProvider>
  )
}

This is my Context.tsx file:

import { createContext, useState } from "react"

import Light from "../styles/themes/Light"
import Dark from "../styles/themes/Dark"

interface Props {
  theme: any;
  setTheme: any;
  handleTheme(): void;
}

export const Context = createContext<Props>(null)

export default function ContextProvider({ children }) {
  const [theme, setTheme] = useState(Dark)

  function handleTheme() {
    setTheme(theme.title === "Dark" ? Light : Dark)
  }

  return(
    <Context.Provider 
    value={{
      theme,
      setTheme,
      handleTheme
    }}
    >
      {children}
    </Context.Provider>
  )
}

I've been getting this error and I'm not sure how to solve it.

Can someone help me?



Solution 1:[1]

The line where you use 'createContext' in your ContextProvider component needs to have an initial object based on your interface 'Props' and not null.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 RandomPerson