Friday, May 28, 2021

Component LifeCycle and State of React Native

 LifeCycle and State of React Native


*Please open this tab in desktop mode to see the codes below*

The two very important concepts in React Native are: 

  • LifeCycle of a React Component
  • State of a React Component
Every React Component rendered on the screen also has a lifecycle.

A React Component has the following stages in its lifecycle:
  • Mounting: This is when the React Components are created and rendered on the screen.
  • Updating: This is when the components are updated. For example, their prop values are changed. 
  • Unmounting: This is when the components are removed from the screen. 
‘componentDidMount()’ and ‘render()’ are two functions which automatically get called at the Mounting Stage of a component.

We wrote a console log message inside ‘componentDidMount()’ function and ran the code.



Now, we are going to learn how the state of a component is declared and accessed. 
  • State of a component is declared inside the constructor. 
  • ‘super()’ is used in the constructor to inherit the properties of the Component Class.

We wrote a function which changes the state of the counter by incrementing the current counter state by 1.


We created a Button which calls this function.


We logged a message inside the ‘ComponentDidUpdate()’ to see if the component is updating.



We wrote code to increment the counter on its own every 1s or 1000 ms using the ‘setInterval()’ function to call the ‘incrementCounter’ every second. We used the function inside of ‘componentDidMount()’.



We changed the color of a button with a random color, every time the button is clicked.



Codes:

Video:






Previous Post
Next Post

post written by:

0 Comments: