Search code examples
reactjsreduxreact-routerlifecyclereact-component

Alternative to componentWillReceiveProps for my particular use case


Since componentWillReceiveProps will be deprecated, I have heard alternatives to use componentDidUpdate, but the problem is componentDidUpdate will also be invoked on state changes as well. Now, most common answers to this question is to compare the previous and current props and do the required action.

But, I want to do certain actions whenever prop changes regardless of whether prop is same as the previous or not.

An example for such a use case would be like this.

Use case 1: I have a search bar on the top of my page, when user types in the search bar and then the search button is clicked, all the other components have to do certain actions. So, when an a string is searched, I used to set a state in redux. And all the other components would get to know these changes from componentWillReceiveProps. Now I wouldn't check for if prevProps and currentProps were the same. Each time when componentWillReceiveProps is invoked, I'd do the certain actions, because, if the user removed the string searched, and retypes the same string, and clicks on the search button again, the other components still need to do those actions, even if the searched string is same as the previous one. So comparing current and previous props is not something that I can do here.

Now with componentDidUpdate, if I do those actions without any check, since it also invoked on state changes, it wouldn't work.

Use case 2: Listening to changes in routes, I use React Router which uses location objects. Now I would use componentWillReceiveProps in this case as well, to listen to the location changes and update my component accordingly, regardless of if the same location object is passed again. So, same issue as the previous use case

What would be the ideal way to approach such scenarios?


Solution

  • You can perhaps add an additional field to Redux Store which would convey information that a new action from user happened, such as timestamp of clicking the search button, or a UUID, and then compare in componentDidUpdate with that.