2

I'm working on a website using React. I'm getting this error when using useContext() and useLocation().

import React, { useContext } from "react";
import Layout from "../components/Layout";
import { LangStateContext } from "../context/LangContext";

import { useLocation } from 'react-router';


const PricingPage = () => {
  const { isIndoSelected } = useContext(LangStateContext);
  console.log(isIndoSelected);

  const location = useLocation();


  return (
    <Layout>
      a page
    </Layout>
  );
};

export default PricingPage;

This is the error im getting when i land on the page

useContext is undefined error

Can anyone explain to me why this wont work and what a good workaround would be?

Thanks you

Ferran Buireu
  • 28,630
  • 6
  • 39
  • 67
Sil
  • 33
  • 4
  • Any luck finding a solution ? I've just encountered this problem : useContext becomes undefined when I add useLocation. But if I comment the useLocation line, no more problem... – FlowRan Dec 09 '21 at 15:42

1 Answers1

1

useContext needs Providers to work, so make sure that you have instantiated one that has this component as a direct or indirect child.

Also make sure that the context that you have created to instantiate this provider has this isIndoSelected that you're trying to access.

You can read more about React's Context usage here.

Daniel Baldi
  • 794
  • 1
  • 9
  • Thanks for your reply. I used "useContext" in combination with "isIndoSelected" on many other page without any issue. Its the "useLocation" that breaks it, this is what i don't understand. – Sil Nov 30 '21 at 01:51
  • How are your providers organized? Are you sure that this page is somehow descendant to any provider? – Daniel Baldi Nov 30 '21 at 01:53
  • Yes im sure, other pages and this page works fine without the use of useLocation(). The moment i declare location with useLocation(), useContext is undefined. – Sil Nov 30 '21 at 02:03