Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

262
Views
How to share state between NextJS components

I want to pass a state between pages in Next.js. My App.js is wrapped in a context provider like so

import { useRouter } from 'next/router'
import { ClickProvider } from '../context/clickContext'

function MyApp({ Component, pageProps }) {
  const router = useRouter()
  
  return (
        <ClickProvider>
                <Component {...pageProps} key={router.asPath} />
        </ClickProvider>
  )
}

export default MyApp

Here's my context provider

import { createContext, useState } from 'react';

const MenuContext = createContext()

export const ClickProvider = ({ children }) => {
  const [menuEnterPage, setMenuEnterPage] = useState('');

  return (
    <MenuContext.Provider value={[menuEnterPage]}>
      {children}
    </MenuContext.Provider>
  );
};

export default MenuContext;

Inside my header component I want to set the menuEnterPage to be the path of the page the user tapped the button on and that data to persist between pages.

import Link from 'next/link'
import React, { useContext, useState, useEffect, useRef } from "react";
import { useRouter } from "next/router"
import MenuContext from '../context/clickContext';

export default function Header({mobileHidden, router = useRouter()}) {
    const [isActive, setActive] = useState(mobileHidden);
    const [menuEnterPage, setMenuEnterPage] = useContext(MenuContext);

    const handleToggle = () => {
      setActive(!isActive);
      if (isActive) {
        
      } else {
        setMenuEnterPage(router.asPath)
        console.log(menuEnterPage)
      }
    };

    return (
      <header>
            <button className="md:hidden" onClick={handleToggle}>{isActive ? "Menu" : "Exit" }</button>
    </header>
    );
  }

Currently when I run the project and click the button it fails with error

TypeError: setMenuEnterPage is not a function

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Try to change this

<MenuContext.Provider value={[menuEnterPage]}>

to this

<MenuContext.Provider value={[menuEnterPage, setMenuEnterPage]}>
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!