user11733988
user11733988

Reputation:

Why am I getting "useContext is not a function" or "context is not defined"?

I am trying to use context in my stateless component. I updated my react to v16.8.0 and added useContext, however, I keep getting these two errors and don't know what else to do. Here is my code:

import React, { useState } from "react";
import axios from "axios";
import { LanguageContext } from "./languageContext";
import { useContext } from "react";

function StripeButton() {
  const context = useContext(LanguageContext);
  const stripe = Stripe("pk_live_5PjwBk9dSdW7htTKHQ3HKrTd");

  const [error, setError] = useState();

  const handleClick = () => {
    stripe
      .redirectToCheckout({
...
    });
  };

  return (
    <div>
      <button
        id="UrgentCheckedButtonYES"
        className="btn-primary"
        onClick={handleClick}
      >
        {this.context.main.name}
        <br />
      </button>
      <div>{error}</div>
    </div>
  );
}

export default StripeButton;
StripeButton.contextType = LanguageContext;

Upvotes: 10

Views: 18409

Answers (4)

Antonio Brandao
Antonio Brandao

Reputation: 1452

For those using Next.js: you may get this error if you don't add 'use client' at the beginning of the file consuming context.

Upvotes: 2

Anisur Rahman
Anisur Rahman

Reputation: 41

(Tested this in React 18.)

In App.js File:

import { createContext } from "react";
import ChildComponent from "./components/ChildComponent";

export const Context = createContext("Default Value");

export default function App() {
    const value = "My Context Value"; 

    return (
        <Context.Provider value={value}> 
            <ChildComponent />
        </Context.Provider>
    );
}

In ChildComponent.jsx file:

import { useContext } from "react";
import { Context } from "../App";

function ChildComponent() {
    const value = useContext(Context);
    return <h1>{value}</h1>;
}

export default ChildComponent;

You can have as many consumers as you want for a single context. If the context value changes,then all consumers are immediately notified and re-rendered.

If the consumer isn't wrapped inside the provider, but still tries to access the context value (using useContext(Context) or <Context.Consumer>), then the value of the context would be the default value argument supplied to createContext(defaultValue) factory function that had created the context.

Upvotes: 0

brandonwang
brandonwang

Reputation: 1653

You need to import useContext like this:

import { useContext } from 'react';

Upvotes: 11

lry
lry

Reputation: 748

const { useContext } = React

useContext is exported as method property of React

Upvotes: 3

Related Questions