Lesson 6 - States

6.2 - Managing Components Internal State With UseState

We've already explored the basics of using state. In this chapter, we'll dive a bit deeper, explaining how to update and manage a component's internal state.

To achieve this, you'll need the useState hook. Start by importing useState from the React package to make it available within your component.

For triggering state updates through user interaction, use elements such as text fields, input fields, and buttons. These elements let you capture user input and update the state accordingly.

Follow the below example

import React, { useState }  from 'react';

const App = () => {
 const [num, setNum] = useState(0);

 return (
 <>
 <p>Current number + 5 = {num}</p>
 <button onClick={() => setNum(num + 5)}>Click me</button>
 </>
 );
}

Here, the state num holds a numeric value as its current state, and setNum is the function used to update this state.

Each time you click the button labeled Click me, the setNum() function increments num by 5. This update triggers a re-render of the component to reflect the updated state.

Let's try a different example with an input field:

import React, { useState } from 'react';

const App = () => {
 const [text, setText] = useState("");

 return (
 <>
 <p>Current text = {text}</p>
 <input type='text' onChange={(event) => setText(event.target.value)}></input>
 </>
 );
}

Similar to our previous example, each time the text inside the input field is changed, it updates the state text using the function setText().