Home » Reactjs » How to listen state changes in react.js?

How to listen state changes in react.js?

Posted by: admin November 30, 2017 Leave a comment


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() {

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.

The following lifecycle methods will be called when state changes. You can use the provided arguments and the current state to determine if something meaningful changed.

componentWillUpdate(object nextProps, object nextState)
componentDidUpdate(object prevProps, object prevState)


I think you should be using below Component Lifecycle as if you have an input property which on update needs to trigger your component update then this is the best place to do it as its will be called before render you even can do update component state to be reflected on the view.

componentWillReceiveProps: function(nextProps) {
    likesIncreasing: nextProps.likeCount > this.props.likeCount