How to use multiple global states using the same Context in React Native?

Viewed 670

I'm developing a Mobile Application using React Native. I came up with a thought of, is it possible to use multiple global states using the same Context.

So, I implemented a context like this.

// GlobalStateContext.js

import React, { createContext, useContext, useEffect } from 'react';

const GlobalStateContext = createContext({ globalStateValue: null, setGlobalStateValue: () => {} });

export function useGlobalState (initialValue = null) {
  const { globalStateValue, setGlobalStateValue } = useContext(GlobalStateContext);

  useEffect(() => { setGlobalStateValue(initialValue) }, []);

  return [globalStateValue, setGlobalStateValue];
}

export default function GlobalStateContextProvider (props) {
  const { value, children } = props;

  return (
    <GlobalStateContext.Provider value={value} >
      {children}
    </GlobalStateContext.Provider>
  )
}

In my App.js, I've wrapped my App with the GlobalStateContextProvider.

// App.js

import GlobalStateContextProvider from './path/to/GlobalStateContext';

export default function App() {
  const [globalStateValue, setGlobalStateValue] = useState(null);

  return (
    <GlobalStateContextProvider value={{ globalStateValue, setGlobalStateValue }} >
      // <MyAppContent />
    </GlobalStateContextProvider>
  )
}

Then, I tried to do something like this on some of my screen files.

import { useGlobalState } from '../path/to/GlobalStateContext';

const [myState1, setMyState1] = useGlobalState('State 01');
const [myState2, setMyState2] = useGlobalState('State 02');

But, there are NO TWO SEPARATE global states. I know there should do something more in the implementation if it is possible to achieve what I want.

So, is this thing is possible? When using useState hook, we can do like,

const [myState1, setMyState1] = useState('State 01');
const [myState2, setMyState2] = useState('State 02');

In this case, we have TWO SEPARATE local states.

Like this, I want to know if it is possible to define some GLOBAL STATES and use them.

0 Answers
Related