this of a React component is not a best practice. While it works, there are more desirable ways to accomplish the same tasks. When holding on to an instance of
this, the reference could go stale if the component is remounted. Also, since it's not a best practice, as React evolves, it might become more troublesome.
A React application tries to encapsulate all of its state, so that what is rendered is predictable. A big part of what makes React great is that the data flow is generally easy to follow: events trigger
setState, data flows down, a new tree is rendered.
From what I understand in this situation, there are two possible paths for the
- The server renders
flash_messages before the HTTP response has been sent, or
- A Rails-JS bridge is sending
flash_messages via XHR to the app without refreshing.
In the first case, when our React app is mounted, it can consume these flash messages at construction time, and propagate the sate accordingly. There's no need for external code to interface with React--React can just read
flash_messages and do what it needs to.
In the second case, the best approach is that the Rails-JS exposes a listener interface. Then, at React construction time, you can subscribe to events, calling
In summary: It's better for React to subscribe to events and update its state when necessary instead external code referencing an object's