React: How to have a global state
Published in
1 min readMar 16, 2018
You might have heard that you need Redux if you want to have something like global bindable data. But I tell you: you don’t. Just use this easy trick.
Imagine our React app is structured like this:
<App>
<Page>
<h1>{/* Here should be the page's title */}</h1>
</Page>
</App>
The code of the App component looks something like this:
import React from "react";
import Page from "./Page";class App extends React.Component {
constructor() {
this.state = {
pageTitle: "Home";
}
}componentWillMount() {
}render() {
return (
<div>
Awesome app <Page />
</div>
);
}
}
Okay, now get ready for the magic, just put this to componentWillMount()
:
window.globalRef = this;
From now on you have access to the App component from anywhere. So in <Page /> you can now do this:
<h1>{globalRef.state.pageTitle</h1>
And of course you can also use .setState()
:
globalRef.setState({ pageTitle: "new title" });