0

I've tried using setInterval but it cycles way to quick.

Banner images array:

const banner = [Banner, Banner2]

React Hooks:

const [ currBanner, setCurrBanner ] = useState(0)

useEffect:

useEffect(() => {
    if( currBanner > 0 ) {
        setInterval(setCurrBanner(currBanner - 1), 2000) 
    } else {
        setInterval(setCurrBanner(currBanner + 1), 2000) 
    }
}, [currBanner])

Image component:

<img className={classes.banner} src={banner[currBanner]} alt="new menu" />
  • The problem is, if currBanner changes, you create a new interval that keeps on calling, without dismissing the old one. You need to persist the setInterval call in your App state – Keimeno Jul 31 '21 at 12:14
  • `setInterval(setCurrBanner(currBanner - 1), 2000)` **calls** `setCurrBanner(currBanner - 1)` and passes its return value into `setInterval`, exactly the way `a(b())` **calls** `b` and passes its return value into `a`. You want to pass a function into `setInterval`. Also be sure to use the callback version of `setCurrBanner` (not the one you provide a value to directly) so you always see the updated value, and be sure to cancel the interval when the component unmounts. Also, don't make the `useEffect` code depend on `currBanner`. – T.J. Crowder Jul 31 '21 at 12:16
  • 1
    Along these lines: https://pastebin.com/xdkEyKJm, more [here](https://reactjs.org/docs/hooks-reference.html#functional-updates), [here](https://reactjs.org/docs/hooks-reference.html#cleaning-up-an-effect), and in [this very useful article by Dan Abramov](https://amiiy.github.io/a-complete-guide-to-useeffect/). – T.J. Crowder Jul 31 '21 at 12:19
  • 1
    @T.J.Crowder thank you for your comment, it helps a lot. I haven't yet grasped the useEffect hook or the component lifecycle, so I'll read the article tonight. Cheers! – Adityo Fauzaan Jul 31 '21 at 12:38
  • @AdityoFauzaan - My pleasure! :-) – T.J. Crowder Jul 31 '21 at 12:40

0 Answers0