title: NextJS - Sensitive Provider only in specific pages
body: <p>I have a question regarding the usage of Contexts in a Next.js application.</p>
  <p>I wrote one Context (called WalletContext) which loads/stores data from one protected API.</p>
  <pre><code>export function WalletProvider({ children }: WalletProviderProps) {
      const [transactions, setTransactions] = useState&lt;Transactions[]&gt;([]);
      useEffect(() =&gt; {
        // fetch data from API (using JWT)
        setTransactions(...);
      }, []);
  
      return (
        &lt;WalletContext.Provider value={{ transactions }}&gt;
          {children}
        &lt;/WalletContext.Provider&gt;
      );
    }
  
    export const WalletContext = createContext({} as WalletContextData);
  
    export const useWallet = () =&gt; useContext(WalletContext);
  </code></pre>
  <p>To use this context, I found two approaches:</p>
  <p><strong>Approach 1: surround the entire App</strong></p>
  <p>File <code>_app.tsx</code>:</p>
  <pre><code>&lt;WalletProvider&gt;
    &lt;Component {...pageProps} /&gt;
  &lt;/WalletProvider&gt;
  </code></pre>
  <p>Pros:</p>
  <ul>
  <li>only one API request is made when navigating between protected pages (the state persists).</li>
  </ul>
  <p>Cons:</p>
  <ul>
  <li>exposing the Provider for non-authenticated users, in non-protected pages</li>
  <li>having to add if(s) inside the provider to check the user is authenticated in order to decide if it is necessary to call the API or not</li>
  </ul>
  <p><strong>Approach 2: not surround the App, but only the specific pages or components</strong></p>
  <p>File <code>protected-page-1.tsx</code>:</p>
  <pre><code>&lt;WalletProvider&gt;
    &lt;Page1 /&gt;
  &lt;/WalletProvider&gt;
  </code></pre>
  <p>File <code>protected-page-2.tsx</code>:</p>
  <pre><code>&lt;WalletProvider&gt;
    &lt;Page2 /&gt;
  &lt;/WalletProvider&gt;
  </code></pre>
  <p>File <code>public-page-3.tsx</code>:</p>
  <pre><code>&lt;Page3 /&gt;
  </code></pre>
  <p>Pros:</p>
  <ul>
  <li>exposing the Provider only for authenticated users</li>
  <li>not having to add if(s) to decide if the API should be requested or not</li>
  </ul>
  <p>Cons:</p>
  <ul>
  <li>every time the user navigates from one protected page to another protected page, the API request is performed again (losing the context state)</li>
  </ul>
  <p>Am I missing something? Is there a better way to handle this?</p>