Search code examples
react-nativefunctionpropertiesglobal-variablesreact-class-based-component

Should I use global variables for keeping the session of the current user in react native?


Currently I'm working on a React Native app which requires people to login to the application, I've created the login page, server-side authentication, etc. My question is, how can I save the user login information in the client-side in a manner that I can access it throughout the app? Is it a bad practice to save the username and password in a global variable, so I can use them to authenticate the user whenever they visit/change pages in the application (This approach makes me have to write the entire app code in a single file though), or should I try to find a way to pass the user data via react native props on different page rendering functions and access it in other pages?


Solution

  • We can use Context API or react-redux to store the user data and any other data to access it globally at the app level.

    Check out the example to implement Context API

    https://blog.logrocket.com/a-deep-dive-into-react-context-api/

    Check out the below for Redux implementation

    https://react-redux.js.org/

    To store the user data in the app data we also can use AsyncStorage npm

    Check out the docs for Async Storage:

    https://react-native-async-storage.github.io/async-storage/docs/install/