3

For a React application that needs to refresh parts of Redux state tree presented to the user in set intervals, are there any downsides to just using setTimeout() to trigger the Redux action creator (for example inside a ComponentDidMount() lifecycle method)and get a json from an endpoint instead of using a proper polling framework such as Meteor.

One use case I can think of is to refresh the user inbox for new messages.

James
  • 3,597
  • 11
  • 41
  • 76
  • `setInterval` ? – Agney Apr 03 '18 at 08:48
  • 1
    It sounds like a matter of design. You can use both: an event triggered approach when a mail is received or refresh it every few seconds. It really depends. See [here](https://medium.com/@machadogj/timers-in-react-with-redux-apps-9a5a722162e8) for pros and cons of different approaches, and here for some refresh solutions on react and/or redux: https://stackoverflow.com/questions/39426083/update-component-every-second-react – vahdet Apr 03 '18 at 08:56
  • In such a case either you poll the data every few seconds, using setInterval defined in componentDidMount or use sockets – Shubham Khatri Apr 03 '18 at 08:57
  • Just make sure you `clearInterval` when the component gets unmounted. And the reducer needs to be aware of a potential action that arrives **after** the component was already unmounted. – timotgl Apr 03 '18 at 12:02

2 Answers2

3

It is generally advised to move your async stuff to redux-middleware:

  • to make your components are "just" a view layer.
  • this also makes your components "cleaner" and easier to test.
  • you can avoid incidentally introducing bugs like memory leaks. For example:
  • if a Promise has setState in a then function then it is not guaranteed that component will still be mounted when Promise resolves.
  • the same with setTimeout or setInterval - someone may forget to unsubscribe from them when component unmounts and react will throw error.
  • people often get confused how to properly use react lifecycle (that's why react deprecated componentWillMount, componentWillUpdate and componentWillReceiveProps).
  • Libraries like redux-saga or redux-observable make such async task easy to accomplish.

However... if you have a very simple situation then moving your code trough middleware may add unnecessary complexity. So, in the end, it's best to do what will be easier to understand and handle in future.

Tomasz Mularczyk
  • 34,501
  • 19
  • 112
  • 166
-1

i recommended you to use Libraries like redux-saga and use generator es6 (yield)