They’re very different things
Global variable
You do global.variavel
indicates that you are declaring a global variable that by itself implies several problems. See Why using global variables is not a good practice?.
Global variable can bring you several headaches in the future because any external function would have access to the same.
Context API
To Contextapi not by far replaces the Redux, Redux is much more than just sharing states. Enter performace and other side effects improvements.
In short, contextApi you can pass data from a parent component to one that is his child, not needing to go through the whole tree.
Normally you have to go from father to son by following the tree. With Context you can go straight to what you need. See a practical example taken from the React documentation
class App extends React.Component {
render() {
return <Toolbar theme="dark" />;
}
}
function Toolbar(props) {
return (
<div>
<ThemedButton theme={props.theme} />
</div>
);
}
class ThemedButton extends React.Component {
render() {
return <Button theme={this.props.theme} />;
}
}
Here I need to pass the props theme
for the component ToolBar
for him to pass to the child component ThemedButton
. You didn’t need the ToolBar
to mediate. But it has to pass to him even so.
With the Context you can go straight to what you need. See an example
const ThemeContext = React.createContext('light');
class App extends React.Component {
render() {
return (
<ThemeContext.Provider value="dark">
<Toolbar />
</ThemeContext.Provider>
);
}
}
function Toolbar(props) {
return (
<div>
<ThemedButton />
</div>
);
}
class ThemedButton extends React.Component {
static contextType = ThemeContext;
render() {
return <Button theme={this.context} />;
}
}
In this example note that the component Toolbar
does not pass any props down (child component). The son (Themedbutton), already has direct access to it.
The difference between global variable and context is noticeable, but in short, the context can only be passed to components below. Any external component of the tree cannot access this value. Unlike a global variable, any corner can access it.
Answering the questions
For status sharing use Contextapi, avoid using global variables as much as possible.
Why?
The answer lies in the link I placed of global variables. But basically, you avoid headache, sometimes you can declare the same name and modify thinking that that variable is in a scope, but in reality is changing the entire functionality of the application.