Let's say that I want to control the loading state of my app by calling the method from outside of the app like so:
setLoading(true)
I have implemented a functional component for which something like that works:
import React from 'react';
function App() {
const [loading, setLoading] = React.useState(true);
window.setLoading = (isLoading) => { setLoading(isLoading) };
if (loading) return 'Loading...';
return 'App content';
}
I believe however that mapping the setLoading()
to window
is not the best approach. Is it possible then to do it differently?
If I had a class component, it would look like this:
import React from 'react';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
loading: true,
}
}
setLoading = (loading) => {
this.setState({ loading });
}
render() {
return(this.state.loading ? 'Loading...' : 'App content');
}
}
Then upon rendering I would use callback ref to make the whole component with all it's methods available.
<App ref={(app) => { window.app = app }} />
app.setLoading(true)
This approach also pollutes the global scope but it's more concise - the component is exposed as a whole.
As neither of the approaches is optimal, which one should I use? Is there maybe something better?