React
Lesson 1 - Introduction
Lesson 3 - Components In React
Lesson 4 - Props
Lesson 5 - Hooks
Lesson 7 - Conditional Rendering
Lesson 8 - Styling In React
Lesson 9 - Forms In React
Lesson 10 - `UseEffect` Hook
Lesson 11 - Web Service Calls In React
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()
.