React JS Tutorial #7: the useEffect Hook
Welcome to the seventh tutorial in our React JS series! In this tutorial, we will be diving into the useEffect Hook in React.
The useEffect Hook is a powerful feature in React that allows you to perform side effects in your functional components. This can include anything from fetching data, updating the DOM, subscribing to events, and more.
Here’s a basic example of how to use the useEffect Hook:
import React, { useEffect } from 'react';
function MyComponent() {
useEffect(() => {
// Perform side effects here
console.log('Component mounted');
return () => {
// Clean up code here
console.log('Component unmounted');
};
}, []);
return Hello World!;
}
In the example above, we have a functional component called MyComponent. Within the useEffect Hook, we are logging ‘Component mounted’ when the component is mounted, and ‘Component unmounted’ when the component is unmounted.
The useEffect Hook also takes a second argument, which is an array of dependencies. If one of the dependencies changes, the effect will re-run. If you leave the array empty, the effect will only run once when the component mounts.
That’s it for this tutorial on the useEffect Hook! We hope you found it helpful and will be incorporating it into your React projects. Stay tuned for more tutorials in our React JS series!
Showing how to use Fetch inside useEffect in this video was super helpful!