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.

4
  • setInterval ? Commented Apr 3, 2018 at 8: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 for pros and cons of different approaches, and here for some refresh solutions on react and/or redux: stackoverflow.com/questions/39426083/… Commented Apr 3, 2018 at 8:56
  • In such a case either you poll the data every few seconds, using setInterval defined in componentDidMount or use sockets Commented Apr 3, 2018 at 8: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. Commented Apr 3, 2018 at 12:02

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

-1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.