2

I'm using setInterval in useEffect. When use not actively using tab, I't requesting like forever. It causing some memory issue. I have to, fetch data in every 3000ms, also stop it when user is not using this tab actively. How can I do such a thing?

I tried to use document.visibiltyState and I couldn't worked it.

My code:

useEffect(() => {
    try {
        const interval = setInterval(() => {
            getTransactionGroupStats()

            getTransactionGroups()

        }, 3000)

        getBinanceBalanceStats()

        return () => {
            clearInterval(interval)
        }
    } catch (error) {
        console.error(error)
    }
}, [])
farukbigez
  • 170
  • 1
  • 10
  • 1
    Does this answer your question? [Check if the browser tab is in focus in ReactJS](https://stackoverflow.com/questions/49902883/check-if-the-browser-tab-is-in-focus-in-reactjs) – kennarddh Aug 09 '22 at 13:32

2 Answers2

0

Another alternative and a little more scalable could be that you create a custom hook to see if the user is active or not and every time it changes you execute the useEffect

useActive.ts

export const useActive = (time: number) => {
    const [active, setActive] = useState(false)
    const timer: any = useRef()
    const events = ['keypress', 'mousemove', 'touchmove', 'click', 'scroll']

    useEffect(() => {
        const handleEvent = () => {
            setActive(true)
            if (timer.current) {
                window.clearTimeout(timer.current)
            }
            timer.current = window.setTimeout(() => {
                setActive(false)
            }, time)
        }

        events.forEach((event: string) => document.addEventListener(event, handleEvent))

        return () => {
            events.forEach((event: string) => document.removeEventListener(event, handleEvent))
        }
    }, [time])

    return active
}

YourApp.tsx

const active = useActive(3000)

useEffect(() => {
   if(active){
     try {
            const interval = setInterval(() => {
            getTransactionGroupStats()

            getTransactionGroups()

        }, 3000)

        getBinanceBalanceStats()

        return () => {
            clearInterval(interval)
        }
    } catch (error) {
        console.error(error)
    }

  }
}, [active])
0

I solved with this approach: https://blog.sethcorker.com/harnessing-the-page-visibility-api-with-react/

export function usePageVisibility () {
const [isVisible, setIsVisible] = useState(!document.hidden)
const onVisibilityChange = () => setIsVisible(!document.hidden)

React.useEffect(() => {
    document.addEventListener('visibilitychange', onVisibilityChange, false)

    return () => {
        document.removeEventListener('visibilitychange', onVisibilityChange)
    }
})

return isVisible
}
farukbigez
  • 170
  • 1
  • 10