Beyond React
You might not be aware that an import is global already. If you export an object (singleton) it is then globally accessible as an import statement and it can also be modified globally.
If you want to initialize something globally but ensure its only modified once, you can use this singleton approach that initially has modifiable properties but then you can use Object.freeze after its first use to ensure its immutable in your init scenario.
const myInitObject = {}
export default myInitObject
then in your init method referencing it:
import myInitObject from './myInitObject'
myInitObject.someProp = 'i am about to get cold'
Object.freeze(myInitObject)
The myInitObject will still be global as it can be referenced anywhere as an import but will remain frozen and throw if anyone attempts to modify it.
Example of react state using singleton
https://codesandbox.io/s/adoring-architecture-ru3vt (see UserContext.tsx)
If using react-create-app
(what I was looking for actually) In this scenario you can also initialize global objects cleanly when referencing environment variables.
Creating a .env file at the root of your project with prefixed REACT_APP_ variables inside does quite nicely. You can reference within your JS and JSX process.env.REACT_APP_SOME_VAR as you need AND it's immutable by design.
This avoids having to set window.myVar = %REACT_APP_MY_VAR% in HTML.
See more useful details about this from Facebook directly:
https://facebook.github.io/create-react-app/docs/adding-custom-environment-variables
Answer from King Friday on Stack OverflowBeyond React
You might not be aware that an import is global already. If you export an object (singleton) it is then globally accessible as an import statement and it can also be modified globally.
If you want to initialize something globally but ensure its only modified once, you can use this singleton approach that initially has modifiable properties but then you can use Object.freeze after its first use to ensure its immutable in your init scenario.
const myInitObject = {}
export default myInitObject
then in your init method referencing it:
import myInitObject from './myInitObject'
myInitObject.someProp = 'i am about to get cold'
Object.freeze(myInitObject)
The myInitObject will still be global as it can be referenced anywhere as an import but will remain frozen and throw if anyone attempts to modify it.
Example of react state using singleton
https://codesandbox.io/s/adoring-architecture-ru3vt (see UserContext.tsx)
If using react-create-app
(what I was looking for actually) In this scenario you can also initialize global objects cleanly when referencing environment variables.
Creating a .env file at the root of your project with prefixed REACT_APP_ variables inside does quite nicely. You can reference within your JS and JSX process.env.REACT_APP_SOME_VAR as you need AND it's immutable by design.
This avoids having to set window.myVar = %REACT_APP_MY_VAR% in HTML.
See more useful details about this from Facebook directly:
https://facebook.github.io/create-react-app/docs/adding-custom-environment-variables
Why don't you try using Context?
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. You only have to specify childContextTypes and getChildContext in the parent component and thereafter you can use/modify this from any component by just specifying contextTypes in the child component.
However, please take a note of this as mentioned in docs:
Just as global variables are best avoided when writing clear code, you should avoid using context in most cases. In particular, think twice before using it to "save typing" and using it instead of passing explicit props.
Best way to initialise a global variable?
Storing non-state variables in functional components
How to access a Global variable in React JS functional component?
reactjs - React when to use global variables instead of states - Stack Overflow
Videos
Hi i have a package A with some helper functions and UI component, package A exports UI component and helper functions idependent of each other. I am importing this package in a react app. In the package A i want to initialise a global variable based on which I want to modify the behaviour of some helper functions. what is the best way to set that variable from react app? should i create a global config object and pass it from the react app or is there any better way to handle this problem?
The useRef hook is not just for DOM refs, but can store any mutable value you like.
Example
function FunctionalBar(props) {
const [foo] = useState(new Animated.Value(0));
const _foo = useRef(0);
function showFoo() {
let anim = Animated.timing(foo, { toValue: 1, duration: 1000, useNativeDriver: true });
anim.start(() => console.log(_foo.current));
}
useEffect(() => {
function _onChangeFoo({ value }) {
_foo.current = value;
}
foo.addListener(_onChangeFoo);
showFoo();
return () => foo.removeListener(_onChangeFoo);
}, []);
return <View />;
}
You can use useRef hook (it's the recommended way stated in docs):
- Declaring variable:
const a = useRef(5) // 5 is initial value - getting the value:
a.current - setting the value:
a.current = my_value
Global variables are bad design within react. Use Context instead https://reactjs.org/docs/context.html
Y would you? It doesnt make any sense. Alot of anti patterns at onces. But the way of doing It Is
Global === Window
const Comp = props => {
const [get, set]= React.useState("");
React.useEffect(()=>{
set(window.Designer.nodes.NODE_FROM.dataSource);
},[window.Designer]);
return (<div/>)
};
The reason why you use state instead of a variable outside the component is because of re-rendering.
If you do not use state, the component will not be updated with the new data returned from your api.
In addition, the correct way to use useEffect is as follows (commented), if you intend to update the data only once.
const [ cityList, setCityList ] = useState([]);
function Component(){
useEffects(()=>{ //<-- remove async here as it's not allowed.
const getData = async () => {
const data = await loadCities();
setCityList(data)
}
getData();
},[]); //<---- add a empty dependency so it only called once when component mounts
...
}
We usually use variable outside component if it doesn't change.
const initialData = ['a','b','c']
component A = () => {
// it's fine to use initialData out of the component because it doesn't change.
}
Of course, there are also times where we can use variable outside the component that can change over time. But only if the rendering of the component does not depend on it. (e.g. using a global variable to track a setTimeout)
Yes, don't use that method.
You can set a state to keep the values if they can change:
function Component() {
const [cityList, setCityList] = useState()
useEffect(async () => {
if (!cityList) {
const response = await loadCities();
setCityList(response);
}
}, [cityList]);
...
}
Check out this example from the React doc: https://reactjs.org/docs/faq-ajax.html#example-using-ajax-results-to-set-local-state
If the data don't change you can declare a variable inside the component:
function Component() {
const cityList = []
...
}
The hook useMemo that you have quoted is an optimization. It can be used to avoid unnecesary computations because it stores a memoized value.
useMemo is helpful when you have expensive calculations that depends on another values.
Check out the official doc about: https://reactjs.org/docs/hooks-reference.html#usememo
Hello!
I have implemented a search functionality in which I am inputting a search text and in an input field and then searching for the same in the chat window. I am also keeping track of total number of search result using a variable named count;
Earlier I used useState to set/update the count but I found that whenever it used to update the state of count , it was re rendering the entire component making other values to initial ones, which caused problems.
So, in react.js , can we use a global variable eg: count for keeping track of search result or is it the case that we must use useState to increment/keep track of the current count value?
Sorry if you're being bombarded with newbie questions everyday, but I'm confused af.
Are props objects that represent the components' data?
Why use props instead of global variables?
Been reading around but can't find a post that makes me understand fully.
Also, just noticed this but, shouldn't this sub's description say "React by Meta" instead of "React by Facebook"?