Using the useEffect Hook
In React, the useEffect
Hook is used to perform side effects in functional components. Side effects can include data fetching, subscriptions, or manually manipulating the DOM.
The useEffect
Hook takes two arguments: a callback function that defines the side effect, and an optional array of dependencies. The callback function will be called after the component is rendered and re-rendered.
Here's an example of how to use the useEffect
Hook:
1import React, { useEffect } from 'react';
2
3const ExampleComponent = () => {
4 useEffect(() => {
5 // Perform side effect here
6 console.log('Component mounted');
7
8 return () => {
9 // Clean up side effect here
10 console.log('Component unmounted');
11 };
12 }, []);
13
14 return (
15 <div>
16 <h2>Example Component</h2>
17 <p>This is an example component that demonstrates the useEffect Hook.</p>
18 </div>
19 );
20};
In the example, we define an ExampleComponent
that uses the useEffect
Hook. Inside the useEffect
Hook's callback function, we perform a side effect by logging 'Component mounted'. We also provide a cleanup function by returning a function from the callback that logs 'Component unmounted'.
The useEffect
Hook is often used to handle subscriptions or fetch data from an API. It can also be used to perform cleanup operations when the component is unmounted.
Try adding your own side effect and cleanup function to the ExampleComponent
. You can use the console.log
function to log messages to the browser console.
xxxxxxxxxx
import React, { useEffect } from 'react';
const ExampleComponent = () => {
useEffect(() => {
// Perform side effect here
console.log('Component mounted');
return () => {
// Clean up side effect here
console.log('Component unmounted');
};
}, []);
return (
<div>
<h2>Example Component</h2>
<p>This is an example component that demonstrates the useEffect Hook.</p>
</div>
);
};