Using the useState hook in React: Make it work for you
Discover the power of the useState hook on react for managing component state effortlessly. with useState, you can easily create and update state variables, enabling dynamic and interacting user interfaces. Learn how to leverage the useState hook`s simplicity and flexibility to enhance your React applications.
The useState hook is a React hook that allows you to manage state in functional components. It is a very powerful tool that can be used to create complex and dynamic user interfaces.
What is State
- State is any data that changes over time in your application. For example, the number of items in a shopping cart or the current value of a text input are both examples of state.
How does useState work?
The useState hook takes two arguments: an initial state value and a function to update the state. The hook returns an array with two values: the current state value and a function to update the state.
For example, the following code creates a state variable called counter
and initializes it to 0:
const [counter, setCounter] = useState(0);
The counter
variable can then be used to access the current value of the counter, and the setCounter
function can be used to update the value of the counter.
Pros of useState
State is managed in functional components, which makes code more reusable and easier to test.
State can be updated without having to create a new component.
State is automatically memoized, which prevents unnecessary re-renders.
Cons of useState
State can be difficult to manage, especially in complex applications.
State can be a source of bugs, if it is not used correctly.
State can make your application slower, if it is not used efficiently.
Example: The following code shows an example of how to use the useState hook to create a simple counter:
import React, { useState } from 'react';
const Counter = () => {
// Declare a state variable called "count" and initialize it to 0
const [count, setCount] = useState(0);
// Event handler to increment the count
const increment = () => {
setCount(count + 1); // Update the count state
};
// Event handler to decrement the count
const decrement = () => {
setCount(count - 1); // Update the count state
};
return (
<div>
<h2>Counter: {count}</h2>
<button onClick={increment}>Increment</button>
<button onClick={decrement}>Decrement</button>
</div>
);
};
export default Counter;
Now Lets take Some Advance Example To understand It in Much Details:
We Will Fetch Github Profile Example.
If the code were written together and commented instead of separately, the sections would be easier to understand
import React, { useState, useEffect } from 'react';
import './Style.css';
const GitHubProfile = () => {
const [username, setUsername] = useState(''); // State for storing the entered GitHub username
const [userData, setUserData] = useState(null); // State for storing the user data fetched from API
const [isLoading, setIsLoading] = useState(false); // State for tracking the loading state
const [error, setError] = useState(null); // State for storing any error that occurs during API fetch
const [repositories, setRepositories] = useState([]); // State for storing the fetched repositories
useEffect(() => {
const fetchUserData = async () => {
try {
setIsLoading(true);
const response = await fetch(`https://api.github.com/users/${username}`);
const data = await response.json();
setUserData(data); // Update the user data state with the fetched data
setIsLoading(false);
} catch (error) {
setError(error.message); // Update the error state if an error occurs during API fetch
setIsLoading(false);
}
};
const fetchRepositories = async () => {
try {
setIsLoading(true);
const response = await fetch(`https://api.github.com/users/${username}/repos`);
const data = await response.json();
setRepositories(data); // Update the repositories state with the fetched data
setIsLoading(false);
} catch (error) {
setError(error.message); // Update the error state if an error occurs during API fetch
setIsLoading(false);
}
};
if (username) {
fetchUserData(); // Fetch user data if a username is provided
fetchRepositories(); // Fetch repositories if a username is provided
}
}, [username]);
const handleSearch = () => {
setError(null);
setUserData(null);
setRepositories([]);
if (username) {
setUsername(username); // Set the entered username as the state value
} else {
setError('Please enter a username'); // Display an error if no username is entered
}
};
return (
<div className="container">
<h2>GitHub Profile</h2>
<div className="search">
<input
type="text"
value={username}
onChange={(e) => setUsername(e.target.value)}
placeholder="Enter GitHub username"
/>
<button onClick={handleSearch}>Search</button>
</div>
{isLoading && <p>Loading...</p>} {/* Display a loading message if the API request is in progress */}
{error && <p>Error: {error}</p>} {/* Display an error message if an error occurs during API fetch */}
<div className="profile-repo-section">
{userData && (
<div className="profile-section">
<div className="card">
<h3>{userData.login}</h3>
<img src={userData.avatar_url} alt="Avatar" className="avatar" />
<p>Followers: {userData.followers}</p>
<p>Repositories: {userData.public_repos}</p>
</div>
</div>
)}
{repositories.length > 0 && (
<div className="repositories-section">
<h4>Repositories:</h4>
<div className="repo-list">
{repositories.map((repo) => (
<div key={repo.id} className="repository">
<p>{repo.name}</p>
</div>
))}
</div>
</div>
)}
</div>
</div>
);
};
export default GitHubProfile;
Lets Understand All Steps Of the Code:
Importing Dependencies and CSS:
- We import the
necessary dependencies
, React, useState, useEffect, and the CSS file containing the styles for our component.
Function Component:
- We define a functional component called
GitHubProfile
that represents ourGitHub profile display
.
State Initialization:
- We initialize
multiple state variables
using theuseState hook
: username to store the entered GitHub username.
- userData to store the user data fetched from the GitHub API.
isLoading
to track the loading state whilefetching
data.- error to store any error that occurs during the
API
fetch
. - repositories to store the
fetched
repositories
.
useEffect Hook:
- We use the
useEffect
hook to fetch user data and repositories whenever the username state changes. - Inside the effect, we define two async functions, fetchUserData and fetchRepositories, to fetch the respective data.
- In
fetchUserData
, we make anAPI
call tofetch user
data using theGitHub API endpoint
with the provided username. - In
fetchRepositories
, we make an API call to fetch repositories using theGitHub API
endpoint with theprovided username
. - If a username is provided, we call both the
functions
to fetch the data. - We update the respective state variables (userData and repositories) with the fetched data.
- If an error occurs during the API fetch, we update the error state and set the loading state to false
Search Functionality:
- We define the
handleSearch function
to handle the search action when the Search button is clicked. - It clears any
existing error
, user data, and repositories from the state. - If a username is provided, it sets the username state with the entered value.
- If no username is provided, it sets an error message in the error state.
Render JSX:
- We return the JSX elements to be rendered.
- The main container has the class name “container”.
- We display a heading “
GitHub Profile
” and a search input field along with a Search button. - The input field is controlled by the username state, and its value is updated when the user types.
- On button click, the
handleSearch function
is called.
If the API fetch is in progress (isLoading is true), we display a loading message. - If an error occurs during the API fetch (error is not null), we display the error message.
- Inside the profile-repo-section container, we conditionally render the profile card and repository list.
- If
userData exists
, we render the profile card containing the user’s login, avatar, followers, andrepositories count
. - If
repositories
contain data, we render a section with the heading “Repositories
” and a list ofrepositories
’ names
Export Component:
- We export the
GitHubProfile
component as the default export.
That’s the detailed explanation of the code. It fetches user data and repositories from the GitHub API based on the entered username and displays the information in a profile card and a list of repositories.
AND NOW The MOST AWAITED OUTPUT for All the EFFORTS:
— — — — — — — — — — — — — That`s All for Now — — — — — — — — — — — — — —
If you enjoyed reading this blog, please share it with your friends and make sure to subscribe to our YouTube channel for more exciting content. Help us spread the word about our expertise in MERN stack development, cloud computing, React Native, and Next.js, and stay tuned for more informative articles to come. Together, we can take the tech world by storm!
In the Mern Stack Projects section you can find tutorials, tips, cheat sheets, and other projects. Our talks also focus on React Frameworks like NextJs,AWS Cloud So join us today to keep up with the latest technology🩷
📠 🏅:- Mern Stack Projects
🎦 🥇:- Jara diary — YouTube 🚦
🎦 🥈 :- Errormania — YouTube 🚦
On GITHUB :- raj-28 (Raj) (github.com)
💌 Do Subscribe To Our Mailing List To stay Updated With All New Blogs 👍
…………🚦…🛣… ……………🚧🛑………………..▶……………….️
Use Emojis From Here In Case You Need Any….🚦🛣️🥇🥈🥉🏅🎖️🎦👍