1

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?

MrLoon
  • 831
  • 1
  • 8
  • 16
  • 1
    What do you mean by "outside of the app"? Do you want to use it from another component, or entirely outside of React components? – Eldrax Jul 08 '20 at 10:48
  • 1
    @Eldrax entirely outside of React - for example by running `setLoading(true)` in browser's console. Check out https://codesandbox.io/s/crimson-rgb-tcmjw where I implemented the component. If you open the app in new tab and run the command, the content will change. – MrLoon Jul 08 '20 at 10:58

1 Answers1

1

I think exposing only the required functions to the outside is more concise, compared to exposing the whole component. If you're exposing to the outside anyway, having a React component exposed outside the context of React does not make much sense - instead, something like window.setAppLoading seems more like an external function for controlling the app's state, which is probably what you need.

Basically, if you want to expose a certain function controlling something about your app to the outside, it is cleaner to expose only that, instead of exposing a part of your app's internals.

Eldrax
  • 499
  • 4
  • 12