Search code examples
javascriptreactjsionic-frameworkionic-react

React state resets when routing (Ionic)


I'm trying to use React states in an app-wide context so all my components and pages can access the most important variables in a convenient manner that updates them as well. I've noticed that setting and accessing the state from the context works fine, but whenever the Route changes, my state/context is completely reset to the initial value. I've spent the last two day trying to wrap my head around it, but I'm totally stuck.

This is the declaration of the Global Context itself: GlobalContext.tsx

import { createContext } from "react";

export interface IGlobalState {
    prop1: boolean,
    prop2: string,
    prop2: string,
    [key: string]: any
}

export const initialState: IGlobalState = {
    prop1: true,
    prop2: "foo",
    prop3: "bar",
};

export const GlobalContext = createContext({
    globalState: initialState,
    setGlobalState: (GlobalState: any) => {}
});

I then create a Context provider: App.tsx

import { GlobalContext, initialState } from './hooks/GlobalContext';
...
const App: React.FC = () => {
  const [globalState, setGlobalState] = React.useState(initialState);
  const globalContextState = { globalState, setGlobalState };

  return(
    <IonApp>
      <GlobalContext.Provider value={globalContextState}>
        <IonReactRouter>
          <IonRouterOutlet>
            <Route path="/" exact={true}>
              <Redirect to="/home" />
            </Route>
            <Route path="/home" exact={true}>
              <Home />
            </Route>
            <Route path="/settings" exact={true}>
              <Settings />
            </Route>
         </IonRouterOutlet>
        </IonReactRouter>
      </GlobalContext.Provider>
    </IonApp>
  );
}  

In the components and pages I access the context like so:

import { GlobalContext, IGlobalState, initialState } from '../hooks/GlobalContext';
...
const {globalState, setGlobalState} = useContext(GlobalContext);

setGlobalState((prevState: IGlobalState) => {
  let state = {...prevState};
  state.prop1 = "someValue";
  return state;
});
...
<SomeComponent value={globalState.prop1} />

Again, setting the state itself works fine as does reading from it. But whenever I route to another page, for example <Settings />, the global state gets reset to initialState. Why is that? It's mind boggling to me.

Note: I have tried moving the GlobalContext.Provider outside the <IonApp>-Tag, because I thought maybe the app needs to be a child component so the pages can access the context. That, however, did not work as well.


Solution

  • The problem was how I routed to other pages. I was using href-properties in IonItems, while I should have used routerLink-properties instead.