Home > database >  React: how to get notified when screen appears again?
React: how to get notified when screen appears again?

Time:09-05

Need to get notified when user coming back from an other webpage. Unfortunatelly useEffect like this will not get called:

function BuyTicket(props: BuyTicketProps) {

useEffect(() => {
}, [authnRes, buyTicketData, programId])

User action on the other website has effect on the backend state, so need to fetch backend again.


Shall I add a isRequredToRefresh state, and set it to true in onClick before or after window.location.href is set? But what if it will run before navigation happens?


What is the equivalent of iOS's viewDidAppear in React.js?


When useEffect without parameter should be used? I see it is constantly get called. It has also drawbacks. It can fall in infinite loop.

useEffect(() => {
})

CodePudding user response:

You can use the window object like so :

const onFocus = () => {
    console.log('Im focused !')
}

useEffect(() => {
    //Add a listener on the window object
    window.addEventListener("focus", onFocus);
    //Clean listeners
    return () => {
        window.removeEventListener("focus", onFocus);
    };
}, []);
  • Related