Today, I learned how React works with useState, how to define logic using functions, how to render UI elements, and how to target a particular element to display updated data.
React makes it easier to build interactive user interfaces by updating the UI whenever the state changes.
- Understanding useState in React useState is a React Hook used to store and manage data inside a functional component. When the state changes, React automatically re-renders the component.
Syntax:
const [value, setValue] = useState("");
value – stores the current state.
setValue – updates the state.
useState("") – initializes the state with an empty string.
- Defining the Logic After creating the state, we define a function to perform an action. For example, when a user clicks a button, a function can update the state.
function greet() {
setMessage("Hello, Welcome to React!");
}
Here, the greet() function contains the logic, and setMessage() updates the state.
- Rendering the UI In React, we use return() to render UI elements using JSX. JSX allows us to write HTML-like syntax inside JavaScript.
return (
Click Me
{message}
);
The button and heading are rendered on the page. When the button is clicked, the function updates the state, and React displays the new message.
- Targeting an Element In React, we can display state data inside a specific JSX element using curly braces {}.
For example:
{message}
Here, the
element is the target where the message appears. When the state changes, React updates the displayed text automatically.
- Complete Example import { useState } from "react";
function Greeting() {
const [message, setMessage] = useState("");
function greet() {
setMessage("Hello, Welcome to React!");
}
return (
Greet Me
{message}
);
}
export default Greeting;
How the Code Works
State: useState("") creates an empty message.
Logic: The greet() function updates the message.
Rendering: The return() statement displays the button and heading.
Targeting: The
element displays the updated message.
Re-rendering: React updates the UI after the state changes.
Conclusion
Today, I learned the basic workflow of React: creating state with useState, defining logic using functions, rendering elements using JSX, and displaying updated values in a target element.
Understanding these concepts is an important step toward building interactive React applications.
Top comments (0)