Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using setTimeout() to call Redux actions

Tags:

reactjs

redux

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.

like image 548
James Avatar asked Mar 28 '26 23:03

James


1 Answers

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.

like image 180
Tomasz Mularczyk Avatar answered Mar 31 '26 06:03

Tomasz Mularczyk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!