useEffect Hook Unleashed: Data Fetching and API Calls in React

Welcome to the Fourth article of the series, "React.js". In this article, we'll explore the power of React useEffect
hook, a vital tool for handling side effects in components. We'll understand its syntax, usage, and real-world applications not only this we will make a mini data fetching project as well. By mastering useEffect, you'll write more efficient and organized React components, making your development journey smoother. Get ready to level up your React skills! To find my previous React Articles Series, visit my Blackslate Profile. So now, let's start learning useEffect
and take your React development skills to new heights!
What are Hooks in React?
We have covered this in the Last Article, but just to give an overview, in short, React Hooks is a feature that enables state and other React functionalities in functional components. Before hooks, state and lifecycle logic were mainly used in class components. With hooks, you can manage state and side effects directly in functional components, making them more concise and easier to understand. Hooks promote code reuse and sharing between components, making development more efficient and enhancing the overall React experience for developers, and useEffect Hook is one of them, now let's understand it.
useEffect Hook
The useEffect hook in React allows us to add a state to your functional components. It works like a container where you can store and update data that changes in your app. For example, you can use it to track the number of likes in an email or the name of a user.
The useEffect hook returns two values: the current state and a function to update the state. When you call the update function, React re-renders your component with the new state. This way, you can create interactive and dynamic components without using classes. useEffect hook is mainly used for fetching data from APIs and performing data updates in your React app more efficiently and powerfully.
Understanding useEffect Hook Syntax
Let's understand how to declare the useEffect hook, how to initialize it, how its syntax work, and many more, But don't worry we are going to cover it all by building a mini data fetching project. So let's get started learning the useEffect Syntax.
useEffect Code Snippets:
useEffect( () => {
// code here
};
}, [dependencyArray]);
Let's break down the useEffect syntax and how it works internally in simple terms:
useEffect is a hook that helps us handle side effects in functional components. Side effects are actions that happen outside the regular component rendering, such as fetching data from an API, updating the document title, or setting up event listeners.
The useEffect function takes two arguments:
1) A function that contains the code for the side effect you want to perform.
2) An optional dependency array (we'll explain this later)
Here's how it works:
1) When the component renders, React remembers the effect function you provided to useEffect.
2) After the initial render, the effect function is executed immediately.
3) On subsequent renders, before executing the effect function again, React checks the optional dependency array (if provided).
4) If the dependency array is empty or not provided, the effect function runs after every render.
5) If the dependency array contains variables (like dependencyArray), React compares those variables between the current render and the previous one.
6) If any of the variables in the dependency array have changed since the last render, the effect function runs again. If they haven't changed, the effect is skipped, avoiding unnecessary work.
To sum it up, useEffect ensures that the effect function is executed under the right conditions:
- If no dependency array is provided, the effect runs after every render
- If a dependency array is provided, the effect runs when any of the variables in the array change.
This allows us to perform side effects in a controlled and optimized manner. By using the dependency array wisely, we can ensure that our side effects are triggered only when needed, avoiding unnecessary computations and making our components more efficient.
Building a mini data fetching project using useEffect Hook
Step-by-step process:
1) To use the useEffect hook in a React functional component, you need to import it from the react library. Here's how you can do it -
import { useEffect } from 'react';
2) Setting up the App.js file:
import './App.css';
import { useEffect, useState } from 'react';
import Header from './Header';
function App() {
const [state, setState] = useState(1);
const [data, setData] = useState([]);
useEffect(() => {
// the code that we want to run
async function getData() {
const get = await fetch(`https://hub.dummyapis.com/employee?noofRecords=${state}&idStarts=1001`)
const res = await get.json();
setData(res);
console.log(res);
document.title = `${state} Online Employees` ;
}
getData();
},[state]) // The dependency array
return (
<div className="App">
<div className="main">
<h3>Click Here to Generate more Data = </h3>
<button onClick={() => {setState(state+1)}} >click me {state}</button>
<Header/>
{
data.map((element, index) => {
return(
<div className='data' key={index} >
<h2>{element.firstName}</h2>
<h2>{element.lastName}</h2>
<h2>{element.email}</h2>
</div>
)
})
}
</div>
</div>
);
}
export default App;
Remember to use https://hub.dummyapis.com/employee?noofRecords=${state}&idStarts=1001
API or otherwise you may face errors.
Explanation of the above App.js file
1) Inside the App component function, we initialize two state variables using the useState hook:
state: This state variable keeps track of the number of records to fetch from the API. It is initialized with a default value of 1.
data: This state variable holds an array where we will store the fetched data from the API. It is initialized as an empty array.
2) We used the useEffect hook to fetch data from an API whenever the state variable changes. The effect function is asynchronous, and it fetches data from the URL specified in the getData function.
- The getData function uses the fetch API to make an asynchronous GET request to the specified URL, passing the current value of the state variable to control the number of records to fetch.
- Once the response is received, the data is converted to JSON using
get.json()
. - The fetched data is then stored in the data state variable using
setData(res)
. - The effect function also updates the document title with the number of online employees based on the state variable. (Title of the website will also be changing after every render, isn't it cool! )
3) The useEffect hook has [state] as its dependency array. This means the effect will be triggered whenever the state variable changes. So, whenever the user clicks the "click me" button, the effect will run, fetching new data based on the updated state.
- The return statement renders the JSX that will be displayed on the screen.
- It contains a div with the class App, and inside it, there's another div with the class main.
- The main div contains an h3 tag and a button with an onClick event handler that increases the state variable by 1 when clicked.
The data array is then mapped, and each element is rendered as a div containing the employee's first name, last name, and email.
That's how the App.js file works. It fetches data from the API and renders it on the screen every time the "click me" button is clicked, with the number of records determined by the value of the state variable.
This is how our mini Project will look and work in the end.
How our mini data fetching project works
Whenever the user clicks the "click me" button, the state variable increases by 1, which triggers the useEffect hook. The hook then fetches new data based on the updated state value and updates the data state variable with the newly fetched data. As a result, the new data is rendered on the screen in the div elements in real time live.
Conclusion
In conclusion, we have thoroughly explored the theoretical foundations of the useEffect hook, grasped its syntax, and understood its practical application. Through a mini data fetching project, we harnessed the useEffect hook's power to fetch and display real-time data on the screen. Now equipped with this knowledge, we can efficiently manage side effects, optimize our components, and create dynamic and interactive React applications.
Keep Learning Keep Growing!
Source code available in Github.