How should the new context api work with React Native navigator? How should the new context api work with React Native navigator? reactjs reactjs

How should the new context api work with React Native navigator?


You can make it like this.

Create new file: GlobalContext.js

import React from 'react';const GlobalContext = React.createContext({});export class GlobalContextProvider extends React.Component {  state = {    isOnline: true  }  switchToOnline = () => {    this.setState({ isOnline: true });  }  switchToOffline = () => {    this.setState({ isOnline: false });  }  render () {    return (      <GlobalContext.Provider        value={{          ...this.state,          switchToOnline: this.switchToOnline,          switchToOffline: this.switchToOffline        }}      >        {this.props.children}      </GlobalContext.Provider>    )  }}// create the consumer as higher order componentexport const withGlobalContext = ChildComponent => props => (  <GlobalContext.Consumer>    {      context => <ChildComponent {...props} global={context}  />    }  </GlobalContext.Consumer>);

On index.js wrap your root component with context provider component.

<GlobalContextProvider>  <App /></GlobalContextProvider>

Then on your screen HomeScreen.js use the consumer component like this.

import React from 'react';import { View, Text } from 'react-native';import { withGlobalContext } from './GlobalContext';class HomeScreen extends React.Component {  render () {    return (      <View>        <Text>Is online: {this.props.global.isOnline}</Text>      </View>    )  }}export default withGlobalContext(HomeScreen);

You can also create multiple context provider to separate your concerns, and use the HOC consumer on the screen you want.


This answer takes in consideration react-navigation package.

You have to wrap your App component with the ContextProvider in order to have access to your context on both screens.

    import { createAppContainer } from 'react-navigation'    import { createStackNavigator } from 'react-navigation-stack'    import ProfileContextProvider from '../some/path/ProfileContextProvider'    const RootStack = createStackNavigator({      Home: { screen: HomeScreen },      Profile: { screen: ProfileScreen },    });    const AppContainer = createAppContainer(RootStack)        const App = () => {      return (      <ProfileContextProvider>        <AppContainer />      </ProfileContextProvider>);    }


https://wix.github.io/react-native-navigation/docs/third-party-react-context/

As RNN screens are not part of the same component tree, updating the values in the shared context does not trigger a re-render across all screens. However you can still use the React.Context per RNN screen component tree.

If you need to trigger a re-render across all screens, there are many popular third party libraries such as MobX or Redux.