Adam Arcaro
Adam Arcaro

Reputation: 471

React-Navigation: Call function whenever page is navigated to

I am developing a React-Native app using React-Navigation, and I am using a stack navigator.

How can I call a function whenever a page is navigated to, including on goBack() events? If I place the method in my constructor, it is only triggered on its initial creation, and not when it is attained through goBack().

Upvotes: 6

Views: 6278

Answers (2)

Alireza tk
Alireza tk

Reputation: 475

use Navigation Events I believe you can use did focus and will blur

<NavigationEvents
      onWillFocus={payload => console.log('will focus', payload)}
      onDidFocus={payload => console.log('did focus', payload)}
      onWillBlur={payload => console.log('will blur', payload)}
      onDidBlur={payload => console.log('did blur', payload)}
    />

https://reactnavigation.org/docs/en/navigation-events.html

EDIT 2022

import { useIsFocused } from '@react-navigation/native';

const isFocused = useIsFocused();

React.useEffect(()=>{
 if(isFocused){

   // callback
 }
},[isFocused])

Upvotes: 4

Tholle
Tholle

Reputation: 112867

As you noted the component is never unmounted when changing pages, so you can't rely on the constructor or even componentDidMount. There is a lot of discussion about this topic in this issue.

You could e.g. listen to the didFocus and willBlur events and only render your page when it is focused.

Example

class MyPage extends React.Component {
  state = {
    isFocused: false
  };

  componentDidMount() {
    this.subs = [
      this.props.navigation.addListener("didFocus", () => {
        this.setState({ isFocused: true })
      }),
      this.props.navigation.addListener("willBlur", () => {
        this.setState({ isFocused: false })
      })
    ];
  }

  componentWillUnmount() {
    this.subs.forEach(sub => sub.remove());
  }

  render() {
    const { isFocused } = this.state;

    if (!isFocused) {
      return null;
    }

    return <MyComponent />;
  }
}

Upvotes: 1

Related Questions