In React Native I want to use global variables when I am moving between different screens
Can anyone help me how to achieve it?
The way you should be doing it in React Native (as I understand it), is by saving your 'global' variable in your index. js, for example. From there you can then pass it down using props.
You can declare a global context variable in any of the parent components and this variable will be accessible across the component tree by this. context. varname .
One way to declare a global variable in React is to attach a new variable as the property of the window object. For example, create a window.name variable in the index. js file like this: import React from "react"; import ReactDOM from "react-dom"; import App from "./App"; window.name = "John"; const root = ReactDOM.
The global scope in React Native is variable global. Such as global.foo = foo
, then you can use global.foo anywhere.
But do not abuse it! In my opinion, global scope may used to store the global config or something like that. Share variables between different views, as your description, you can choose many other solutions(use redux,flux or store them in a higher component), global scope is not a good choice.
A good practice to define global variable is to use a js file. For example global.js
global.foo = foo; global.bar = bar;
Then, to make sure it is executed when project initialized. For example, import the file in index.js:
import './global.js' // other code
Now, you can use the global variable anywhere, and don't need to import global.js in each file. Try not to modify them!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With