Skip to content
Advertisement

How to listen state changes in react.js?

What is the angular’s $watch function equivalent in React.js?

I want to listen state changes and call a function like getSearchResults().

componentDidMount: function() {
    this.getSearchResults();
}

Advertisement

Answer

I haven’t used Angular, but reading the link above, it seems that you’re trying to code for something that you don’t need to handle. You make changes to state in your React component hierarchy (via this.setState()) and React will cause your component to be re-rendered (effectively ‘listening’ for changes). If you want to ‘listen’ from another component in your hierarchy then you have two options:

  1. Pass handlers down (via props) from a common parent and have them update the parent’s state, causing the hierarchy below the parent to be re-rendered.
  2. Alternatively, to avoid an explosion of handlers cascading down the hierarchy, you should look at the flux pattern, which moves your state into data stores and allows components to watch them for changes. The Fluxxor plugin is very useful for managing this.
Advertisement