0

i have App.tsx which is app root and then two tabs tab1.tsx and tab2.tsx.

The tab1.tsx has a variable declared as

  const [coins, setCoins] = useState(0)

and tab2.tsx also i have declared the same

  const [coins, setCoins] = useState(0)

but this is just a workaround as of now. how do i have it declared it at just one place be able to share it between the two tabs. i don't think passing it between the tabs as parameter is a good solution.

in ionic angular i used a service to delcare this kind of variables and easily referred then through out the application. what is the solution for ionic-react?

Moblize IT
  • 1,140
  • 2
  • 18
  • 44

1 Answers1

0

Use useContext React Hook. https://reactjs.org/docs/hooks-reference.html#usecontext

1- Create a new file in the project, such as my-context.tsx

import React, { createContext, useState } from "react";

//create the context
export const MyContext = createContext<any>(undefined);

export const MyProvider: React.FC = ({ children }) => {

  const [coins, setCoins] = useState(0)
  
  let state = {
coins,
setCoins
    
  };

  //wrap the application in the provider
  return <MyContext.Provider value={state}>{children}</MyContext.Provider>;
};

export default MyContext;

2- Wrap App.tsx inside <AuthProvider> </AuthProvider> like this:

const App: React.FC = () => {

  return (
    <IonApp>
      <AuthProvider>
        <IonReactRouter>
          ...
        </IonReactRouter>
      </AuthProvider>
    </IonApp>
  );
};

export default App;

3- Every time you want to use this state in other components/pages, import the context and use it like this:

  const {
    coins,
    setCoins
  } = React.useContext(MyContext);

In this way, you share states and set states through out the app.

Ani
  • 788
  • 3
  • 7
  • 21