Global state in React Native

32,570

Solution 1

I usually create a global.js containing:

module.exports = {
   screen1: null,
};

And get the value of the state on the screen

import GLOBAL from './global.js'
constructor() {
    GLOBAL.screen1 = this;
}

Now you can use it anywhere like so:

GLOBAL.screen1.setState({
    var: value
});

Solution 2

Update since React 16.8.0 (February 6, 2019) introduce Hooks.

it is not mandatory to use external library like Mobx or Redux. (Before Hook was introduce I used both of this state management solutions)

you can create global state just with 10 line Source

import React, {createContext, useContext, useReducer} from 'react';
export const StateContext = createContext();
export const StateProvider = ({reducer, initialState, children}) =>(
  <StateContext.Provider value={useReducer(reducer, initialState)}>
    {children}
  </StateContext.Provider>
);
export const useStateValue = () => useContext(StateContext);

extend your app with global state:

import { StateProvider } from '../state';
const App = () => {
  const initialState = {
    theme: { primary: 'green' }
  };
  const reducer = (state, action) => {
    switch (action.type) {
      case 'changeTheme':
        return {
          ...state,
          theme: action.newTheme
        };
      default:
        return state;
    }
  };
  return (
    <StateProvider initialState={initialState} reducer={reducer}>
        // App content ...
    </StateProvider>
  );
}

For details explanation I recommend to read this wonderful medium

Solution 3

There are some alternatives to Redux in terms of state management. I would recommend you to look at Jumpsuit and Mobx. However do not expect them to be easier than Redux. State management is mostly a magical thing and most of the gizmo happens behind the scenes.

But anyways if you feel that you need some global state management, it worths your time to master one of the solutions no matter Redux or Mobx or etc. I would not recommend using AsyncStorage or anything hacky for this purpose.

Solution 4

I usually do globals like this:

I creat an globals.js

module.exports = {
  USERNAME: '',
};

Something like that to store the username then you just need to import :

GLOBAL = require('./globals');

And if you wanna store the Data, lets say you want to save the username just do :

var username = 'test';
GLOBAL.USERNAME = username;

And there you go , you just need to import GLOBAL on the pages you want and use it, just use if (GLOBAL.username == 'teste').

Solution 5

If you are new to react (as me) and got confused by the first answer. First, use a component Class

export default class App extends React.Component {
constructor(props) {
  super(props);
  this.state = {
    walk: true
  };
  GLOBAL.screen1 = this;
}
render() {
  return (
    <NavigationContainer>
      <Stack.Navigator>
      {this.state.walk ? (
        <>
          <Stack.Screen name="WalkThrough" component={WalkThroughScreen} />
        </>
      ) : (
        <Stack.Screen name="Home" component={HomeScreen} />
      )}
    </Stack.Navigator>
    <StatusBar style="auto" />
  </NavigationContainer>
 )
}

Then you can do in any other component (My components are on /components, global is on root):

import GLOBAL from '../global.js'
GLOBAL.screen1.setState({walk:false})
Share:
32,570

Related videos on Youtube

Jamgreen
Author by

Jamgreen

Updated on December 08, 2021

Comments

  • Jamgreen
    Jamgreen over 1 year

    I am developing a React Native application.

    I want to save the user id of the person who is logged in and then check if the user is logged in in every single component.

    So what I am looking for is something like cookies, sessions or global states.

    I have read that I should use Redux, but this seems to be overly complicated and it is very difficult to make it work with react-navigation. It forces me to define actions and reducers for almost everything although the only thing I want is to be able to access a single global state/variable in all components.

    Are there any alternatives or should I really re-structure my entire app to use Redux?

  • sooper about 6 years
    Components like AsyncStorage are for persistence, I think the OP is concerned with managing the state of the app which generally should be in memory.
  • milkersarac
    milkersarac about 6 years
    @sooper , that is why I am not recommending AsyncStorage.
  • sudo
    sudo about 4 years
    This is the best; don't underestimate it for being simple. I fiddled with Redux forever just to get basically the same functionality but with 20X the code and lots of magic (the connect stuff is really jank).
  • Jar
    Jar almost 4 years
    can you put more robust explanations. I'm not sure what you're doing in the render(){Global.screen1state = this}
  • ICW
    ICW almost 4 years
    Doesn't this refer to the react component? If so, better name would be GLOBAL.screen1 = this, since this is the component and this.state is what actually refers to the state associated with the component. @RaphaelEstrada
  • ICW
    ICW almost 4 years
    State management isn't magical by nature. It can be super simple while being maximally effective without being behind the scenes whatsoever, see the above answer by @RaphaelEstrada. You're recommending using an entire library of code, most of which you will never use, when a single javascript object can do the job just as effectively.
  • skilleo
    skilleo over 3 years
    Context is for ReactJS.
  • Laurence
    Laurence over 2 years
    i am a newbie. how do you do this with function component?
  • Yusuf
    Yusuf about 2 years
    how about functional component

Related