title: Next.js - How do I use Provider to Wrap Routes and use Context with Hooks
body: <p>I wrote code similar to the following in create-react-app and I want to know the equivalent for next.js. The code below is my attempt at having a global Context that is available to all pages. The Provider wraps the Links. I get no errors. The problem is inside the <strong>about</strong> page the console.log(state) returns undefined when I expect the Context state. How do I fix this?</p>
  
  <p>Thank you.</p>
  
  <p>pages/index.js</p>
  
  <pre><code>
  import Link from "next/link";
  import {Provider} from './Context';
  
  
  
  
  
  function Index(){
  
  
      return(
  
          &lt;div&gt;
           &lt;Provider&gt;
            &lt;ul&gt;
               &lt;li&gt;&lt;Link href="/"&gt;&lt;a&gt;Home&lt;/a&gt;&lt;/Link&gt;&lt;/li&gt;
               &lt;li&gt;&lt;Link href="/about"&gt;&lt;a&gt;About&lt;/a&gt;&lt;/Link&gt;&lt;/li&gt;
            &lt;/ul&gt;
            &lt;/Provider&gt;
          &lt;/div&gt;
  
      )
  }
  
  export default Index;
  
  </code></pre>
  
  <p>pages/about.js</p>
  
  <pre><code>import { useRouter } from 'next/router';
  import {Context} from './Context';
  import {useContext} from 'react';
  
  
  
  const About= () =&gt; {
  
   const data = useContext(Context);
   console.log(data)
  
    return (
      &lt;div&gt;
  
  
        &lt;p&gt;This is the blog post content.&lt;/p&gt;
  
      &lt;/div&gt;
    );
  };
  
  export default About;
  
  </code></pre>
  
  <p>pages/Context.js</p>
  
  <pre><code>import React, {createContext, useState, useEffect}from 'react';
  
  
  let Context = createContext();
  
  function Provider(props){
  
     const initialState = {
          userID: false,
          user:undefined,
          loading: true,
          authenticated:false
      }
  
      const [state,updateState] = useState(initialState)
  
  
  
  
    return(
  
      &lt;Context.Provider value={{
          state:state
      }}&gt;
  
        {props.children}
      &lt;/Context.Provider&gt;
  
    )
  
  }
  
  
  const Consumer = Context.Consumer;
  export {Provider, Consumer, Context}
  
  </code></pre>