1
useEffect(() => {
      if (params.usersearch === props.search || "random" === props.search) { 
        console.log('same');
        return;
      }else{
        console.log(props.search);
        console.log('Params is :',params.usersearch);
        let api = `https://www.flickr.com/services/rest/?method=flickr.photos.search&api_key=${apiKey}&tags=${params.usersearch}&per_page=24&format=json&nojsoncallback=1`;
        props.handleLoading(true); //changing state
        let fetchedData = axios
          .get(api)
          .then((data) => data.data.photos.photo)
          .catch((err) => console.log(err));
        props.handleData(fetchedData); //changing state
        props.handleSearch(params.usersearch); //changing state
        props.handleLoading(false); //changing state
        const title = document.querySelector("title");
        title.textContent = `Flickr-Photos/${params.usersearch}`;
        }
    },[params.usersearch]);

Hi everyone. I have a question , If my useEffect is running and it in between changes state(as I have mentioned when the props.handleLoading function gets triggered ), so is it gonna stop the and re-run the useEffect method or it is gonna complete the code?

1
  • 2
    Why would it "stop"? This function, in its entirety (barring an error), will execute. This instance of the component will only re-run this function when the dependency passed to useEffect changes. Surely your testing would observe and confirm this?
    – David
    Commented Jul 22, 2022 at 13:50

1 Answer 1

1

This kind of code execution cannot be implicit stopped.

Answer: The useEffect-callback will be called again, even if the previous is not done

You could use a debounce or blocking behavior and cancel/ignore the previous action. UseEffect supports a clean-up method. You could return a function to cancel a timer with a given throttle value (for debounce).

As stated by the react docs

Why did we return a function from our effect? This is the optional cleanup mechanism for effects. Every effect may return a function that cleans up after it. This lets us keep the logic for adding and removing subscriptions close to each other. They’re part of the same effect!

When exactly does React clean up an effect? React performs the cleanup when the component unmounts. However, as we learned earlier, effects run for every render and not just once. This is why React also cleans up effects from the previous render before running the effects next time. We’ll discuss why this helps avoid bugs and how to opt out of this behavior in case it creates performance issues later below.

Solution

Stackblitz Example

0

Not the answer you're looking for? Browse other questions tagged or ask your own question.