Search code examples
javascriptreactjsreact-hooksuse-effect

How to trigger useEffect in React only once AFTER some certain variable gets loaded


I am trying to use useEffect hook in React to trigger some functions only once. I know that this could normally be done by doing

useEffect(() => {
    // some functions
    }
}, [])

However, the functions require some values to be loaded. So, I only want this useEffect to get triggered only ONCE when the value is not empty.

useEffect(() => {
    // some functions
}, [theValue])

This is what I tried, but I know that this will get triggered whenever theValue changes.

How can I change my useEffect to run only ONCE when theValue becomes not empty?


Solution

  • You can use a React ref to hold a boolean if the effect has been triggered yet, and combine that with a conditional test that all the dependencies have been met to trigger the effect.

    const effectTriggeredRef = React.useRef(false);
    
    React.useEffect(() => {
      if (!effectTriggeredRef.current && /* deps conditions */) {
        effectTriggeredRef.current = true;
        // trigger some functions
      }
    }, [...deps]);