Home > database >  useState is executed even dependency doesn't change
useState is executed even dependency doesn't change

Time:11-22

I have to fetch an API when a state changes, i've used useEffect adding the dependency like this

const [ activeLottery, setActiveLottery ] = useState();
useEffect(() => {
    console.log('fetching')
}, [activeLottery])
return (
    <div className="container">
        <Carousel 
            lotteries={ lotteries } 
            isLoading={ isLoading }
            slideClick={ setActiveLottery }
        />
    </div>
);

The Component Carousel has an onClick function which changes activeLottery and it works properly since the state is mutated. But it executes the fetch when the component is rendered. Shouldn't do it when activeLottery changes?

Any hint would be much appreciated.

thanks

CodePudding user response:

By default, useEffect always runs after the first render.

The dependency array in useEffect lets you specify the conditions to trigger it. If you provide useEffect an empty dependency array, it’ll run exactly once.

If you want to make API call when activeLottery changes then write condition inside useEffect.

useEffect(() => {
    if(activeLottery?.length){ // if activeLottery is array then you can check it's length
    // Your API call goes here
    }
    console.log('fetching')
}, [activeLottery])

Additionally, you can check out this awesome StackOverflow answer: https://stackoverflow.com/a/59841947/16420018

And this article by Dan Abramov: https://overreacted.io/a-complete-guide-to-useeffect/

  • Related