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
componentDidUpdate(prevProps,prevState) { if (this.state.buyerId !== prevState.buyerId) { this.props.fetchBuyerData(this.state.buyerId); // some random API to search for details of buyer } }
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.
useEffect(() => { props.fetchBuyerData(state.buyerId); }, [state.buyerId]);
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
:
// deconstruct in declaration function MyComponent({ fetchBuyerData }) { useEffect(() => { // caveat: something is wrong with the use of `this.state` here fetchBuyerData(this.state.buyerId); }, [fetchBuyerData, state.buyerId]); } // deconstruct inside component function MyComponent(props) { const { fetchBuyerData } = props; useEffect(() => { // caveat: something is wrong with the use of `this.state` here fetchBuyerData(this.state.buyerId); }, [fetchBuyerData, state.buyerId]); }