DEV Community

Manoj Kumar Jain
Manoj Kumar Jain

Posted on

React context is lost with useNavigate

I am trying to navigate to a link in my React application.
I am maintaining application state with React useContext hooks
From my landing page, the context is initialized.
On landing page I have a button to navigate to my profile page. For navigation I am using react useNavigation hooks.
The problem is with navigation, the page opens correctly but the react context is lost and it shows blank data.
Question - how can I maintain the context while switching the pages.

import { Routes, Route, Navigate } from "react-router-dom";

import { CZGlobalProvider } from './store/CZGlobalContext';
import CZHeader from './components/Header/CZHeader'
import Explore from "./components/CZWorld/Explore";
import MyProfile from "./components/MyWorld/MyProfile";
import EditMyProfile from "./components/MyWorld/EditMyProfile";

function CApp() {
  return (
    <div className="cmaze">
      <CZGlobalProvider>
        <CZHeader />
        <Routes>
          {<Route path="/" element={<Navigate replace to="explore" 
 />} />
          <Route path="explore" element={<Explore />} />
          <Route path="profile" element={<MyProfile />} />
          <Route path="editprofile" element={<EditMyProfile />} />
        </Routes>
      </CZGlobalProvider>
    </div>
  )
}

export {
  CApp
}




import { CZGlobalContext} from "../../store/CZGlobalContext";
import { Navigate, useNavigate } from "react-router-dom";
const HeaderMenu = () => {
  const {
    appCtx, setAppCtx
  } = useContext(CZGlobalContext);

  const navigate = useNavigate();


  const handleOnClick = async (event) => {
    event.preventDefault();
    console.log('handleOnClick ' + event.target.innerText)
    setAppCtx(
      {
        name: 'Manoj',
        email: 'manoj@testmail.com'
      }
    )
    navigate('/profile')
  }

  return (
    <React.Fragment> 
       <Button variant="contained" size="small" onClick={handleOnClick }>Profile</Button>


    </React.Fragment>
  );
}

export default HeaderMenu;

Enter fullscreen mode Exit fullscreen mode

Top comments (0)