Vince Carter
Vince Carter

Reputation: 946

React Native: where to place global state variables

I am developing my first React Native, and I need again some help. My application has one state - sport, which will be important for components, screens and etc. Accordingly the chosen sport, I will load different styles, images, and api information too. There will be one modal, from which the user can change the sport. The modal now is part of the Header component, which is part of the Screen component.

So my question is how or where to place this sport state variable, so I can access it everywhere and on a change to update the new styles and etc.

The overview of the application is like this:

App.js

    import AppContext from './utility/context';
    
    export default function App() {
        
          const [sport, setSport] = React.useState('soccer');
          const state = {sport, setSport};
        
          return (
             <AppContext.Provider sport={state}>
                <OfflineNotice />
                <Screen />
             </AppContext.Provider>
          );
        }

context.js

import React from "react";

export const AppContext = React.createContext({
    sport: 'soccer', 
    setSport: () =>{}
});

Screen.js

export default function Screen ({children}) {
    return (
        <>
        <Header />
        <SafeAreaView style={styles.screen}>
            <View style={styles.container}>{ children }</View>
        </SafeAreaView>
        <TabNavigator i18n={i18n}/>
        </>
    );
}

In Header.js I will also use that future state, but at the moment there is nothing interesting. But here will be the View, from which the user will change the sport state variable.

HomeScreen.js - it is the first screen of the TabNavigator

export default function HomeScreen({ navigation }) {

  const today = Moment(new Date().getTime()).format('YYYY-MM-DD');
  const [predictions, setPredictions] = useState([]);
  const [loading, setLoading] = useState(true);
  const params = {
    lang: 'en',
    date: today,
    sport: 'soccer',
  };

  ...

}

Here the sport state is hardcoded because I don't know yet how to proceed.

I've heard about Redux, but I haven't used it yet, so I will appreciate if there is any solution not using Redux.

Thank you in advance!

Upvotes: 3

Views: 4573

Answers (1)

Guruparan Giritharan
Guruparan Giritharan

Reputation: 16334

You can achieve this using React-Context

You can simply have a state in the app.js and use context to access it anywhere you need in the app.

First you need to create the context. Its better if its a separate file

const AppContext = React.createContext({sport:'value',setSport=()=>{}});

Here the default values are options but preferred specially when you use typescript to avoid warnings.

Now you have to use this in your app.js like below

export default function App() {
  const [sport,setSport] = React.useState('value');
  
  const state={sport,setSport};
  ...

  return (
    <AppContext.Provider value={state}>
      <OfflineNotice />
      <Screen />
    </AppContext.Provider>
  );
}

You will have to import the context and use the provider as the wrapper setting the value from the local state that you have. Now you can access this anywhere in the tree and modify it if required.

// Accessing the context using the useContext hook, this component should be in the tree and you should import AppContext

const {sport,setSport} = useContext(AppContext);

You can show it like below

<Text>{sport}</Text>

Or set it like below

<Button title="Set Value" onPress={()=>{setSport('value')}}>

This example is just on a string but you can even have an object.

Upvotes: 1

Related Questions