Skip to content
Advertisement

Rewrite useEffect hook from componentDidUpdate lifecycle method

Suppose we have an input for buyer id and we want to fetch the buyer details each time the buyerId is changed. The following code looks like this for class components

JavaScript

But if we want to use useEffect hook inside a functional component how would we control it. How can we compare the previous props with the new props.

If I write it as per my understanding it will be somewhat like this.

JavaScript

But then react’s hooks linter suggests that I need to include props into the dependency array as well and if I include props in the dependency array, useEffect will be called as soon as props changes which is incorrect as per the requirement. Can someone help me understand why props is required in dependency array if its only purpose is to make an API call. Also is there any way by which I can control the previous state or props to do a deep comparison or maybe just control the function execution inside useEffect.

Advertisement

Answer

Deconstruct props either in the function declaration or inside the component. When fetchBuyerData is used inside the useEffect hook, then only it needs to be listed as a dependency instead of all of props:

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement