0

I'm passing a prop necessary to run an API call into my component and I do not want it to run on initial rendering but only once this prop has been updated by a form submission. Even though I'm putting props in the dependency argument it still runs the call on mount. How can I prevent useEffect from automatically running on initial rendering? Maybe there's a completely different method I should be considering?

function GetData(props) {


 const [propsState, propsSetState] = useState('');

 useEffect(() => {

  // Run API Call

 }, [props])
}
gabed123
  • 515
  • 3
  • 8
  • 19
  • https://stackoverflow.com/questions/53179075/with-useeffect-how-can-i-skip-applying-an-effect-upon-the-initial-render – arieljuod Nov 28 '21 at 16:01

3 Answers3

2
const [mounted, setMounted] = useState(false);

useEffect(() => {

  if (!mounted) {
    setMounted(true);
    return;
  }

  // Run API Call

}, [props])
palindrom
  • 18,033
  • 1
  • 21
  • 37
1
const ref = useRef();

useEffect(() => {

  if (!ref.current) {
    ref.current = true
    return;
  }

  // Run API Call

}, [props])
Aryan Moradi
  • 127
  • 5
0

In your return statement use logical && to evaluate if something is updated before run the API in your component.

{propState && <*YourComponent* />}

First Fetch the data, once the data is being retrieve, then update the state in your const[], once it has the value, your component then render the output.