2025-10-07 19:36
Status:
Tags: react.js, javascript, [[]]
Why the Hook?
Why should you use the useEffect hook? useEffect is used to get your React component, in sync with a system outside of React.
Here's an example:
You're creating a video player application in React, we need to hit an outside api to get the news articles to display inside our application. We want to get the video information as soon as our application loads so what we can display it to our users ASAP.
To do this in use effect, first we will invoke the hook with by calling useEffect(<callback function>, <dependency array>), this function takes two parameters. The first is the callback function, where we can write our code that we want executed to get our news api:
() => {
try {
const response = fetch("/api/video");
if (!response.ok) {
throw new Error(Http error! status: ${response.status});
}
const videoApiData = await response.json();
setVideoData(videoApiData);
} catch (error) {
console.log('Error fetching data:', error);
}
}
The second parameter that we pass is called the dependency array, this is how we let it know what we want to keep in sync with, whenever something changes inside our dependency array, our callback function will execute.
If you leave the dependency array empty, it will execute our callback function when the component first mounts.
For us, since we want to get the news data when the component initially loads, here is what our code will look like:
!carbon (1).png
That's how you implement the useEffect hook in React to load data in your application when your component first loads.