Search code examples
reactjscomponentsfrontendobserver-pattern

ReactJS - Triggering Re-render from external Process


Im very new at React and Frontend development. Its literally my first Project now and I have design problem listening to external events. So basically I want to build a UI that only changes on external Events, meaning you control it with another Process (e.g. an AI that triggers the changes). The App should listen to incoming messages and depending on the message it should update the UI.

My idea was to make the Component, that receives the messages from outside, an observable and notify the MainApp of the React-Ui. The following code should give an idea to my approach.

export default class App extends Component {
constructor(props){
    super (props);
    this.state = {mode: "idle"};
    this.observable = new Observable();
    this.observable.add((m) => mode(m));
}

mode(m){
    this.setState({
        mode: m
    });
}

render() {
    return (
        <div>
            <Home/>
            <ComponentA mode={this.state.mode}/>
            <ComponentB mode={this.state.mode}/>
        </div>
    )
}}

My Question now is, Is this a good way to update the UI or are there maybe better ways or pattern that I can use or that are common in Frontend-Development?


Solution

  • Your approach is totally valid, I don't see any issues with it.

    You could try initializing the observable in a lifecycle method instead like componentDidMount. You could even use redux to manage the data passed from the observable.