user2426823
user2426823

Reputation:

ReactJS: How to make a component call a method only the very first it is rendered?

I would like for a component to call a method only once, and only the very first time the component gets rendered. I attempted it in constructor(), thinking that it is supposed to occur only once and only when it is first mounted ever, but looks like whenever that component is rendered again, the constructor() is called again as well.

Is there a way to have a component call a method only once and only the very first time it is rendered?

Thank you

Upvotes: 9

Views: 14967

Answers (3)

fatiha.kafou
fatiha.kafou

Reputation: 81

You could set a variable in localStorage when you first load your page. Then, whenever you render, you simply get and test that variable:

   async componentDidMount() {
      ...
      if(localStorage.getItem('reRender') !== "true") {
          //Processing to do only for the very first render 
          localStorage.setItem('reRender', "true");
      }
   }

You could reset the variable depending on your use case afterwards (for example when logging out):

localStorage.removeItem('reRender');

Upvotes: 0

asayah
asayah

Reputation: 1

you can use getDerivedStateFromProps and pass an empty parameter while you navigate, that triggers the method once after the navigation.

  // caller 
     this.props.navigation.navigate('SOMEWHERE', {})

   // SOMEWHERE
  static getDerivedStateFromProps(nextProps, prevState){
    doSomething()
    return null
   }

Upvotes: 0

Eric Kambestad
Eric Kambestad

Reputation: 139

componentWillMount() gets called pre-render and only once until the page refreshes.

https://facebook.github.io/react/docs/react-component.html#componentwillmount

componentDidMount() gets called immediately after render() and the DOM is available at this time. This will happen only the first time it's loaded until the page refreshes.

https://facebook.github.io/react/docs/react-component.html#componentdidmount

Upvotes: 4

Related Questions