React JS - state in Functional Component

To store initial value in state, we write following code :

const [data,setData] = useState(100)

Here, useState is a React Hook which stores the initial value. data is variable which stores the value and SetData is a variable which stores the updated value.

Example 1 : Store initial value in state & Display Data 














Output :








GitHub :
https://github.com/eramitsinha/React-Dummy/blob/main/src/StateFunctionalComp1.js

Example 2 : Update the Data on Button Click

When user clicks on the button, the data gets updated in state using Event.


Output :








GitHub :
https://github.com/eramitsinha/React-Dummy/blob/main/src/StateFunctionalComp.js

Example 3 : Increment the Value on Button Click

When user clicks on the button, increment the value by +1.


Output :


GitHub :
https://github.com/eramitsinha/React-Dummy/blob/main/src/StateFunctionalComp2.js

INTERVIEW QUESTIONS :
  • Can we use state outside the component?
    No

  • Is state public or private?
    public

Comments