`useEffect` is another built-in hook in React that allows you to add side effects to functional components. Side effects are actions that are not directly related to rendering a component, such as fetching data from an API or subscribing to a WebSocket.
Here’s an example of how to use `useEffect` to fetch data from an API:
jsx import React, { useState, useEffect } from "react"; function DataFetcher() { const [data, setData] = useState(null); useEffect(() => { async function fetchData() { const response = await fetch("https://example.com/data"); const data = await response.json(); setData(data); } fetchData(); }, []); returnData: {data}
; }
In this example, we’re defining a functional component called `DataFetcher` that uses `useState` to define a state variable called `data`, with an initial value of `null`. We’re then using `useEffect` to fetch data from an API and update the `data` state variable when the component mounts.
The `useEffect` function takes two arguments: a callback function that performs the side effect, and an array of dependencies that determines when the effect should be re-run. In this example, we’re passing an empty array as the second argument, which means the effect should only be run once when the component mounts.
You can also use `useEffect` to perform side effects when the component updates or unmounts. Here’s an example of how to use `useEffect` to update the document title when the component updates:
jsx import React, { useState, useEffect } from "react"; function DocumentTitleUpdater(props) { const [count, setCount] = useState(0); useEffect(() => { document.title = `Count: ${count}`; }, [count]); function handleIncrement() { setCount(count + 1); } return (); }Count: {count}
In this example, we’re defining a functional component called `DocumentTitleUpdater` that uses `useState` to define a state variable called `count`, with an initial value of `0`. We’re then using `useEffect` to update the document title with the current count value when the component updates. We’re passing `[count]` as the second argument to `useEffect`, which means the effect should be re-run whenever the `count` state variable changes.
Overall, `useEffect` is a powerful tool in React that allows you to add side effects to functional components and build dynamic and interactive user interfaces. By using `useEffect`, you can create components that perform complex tasks like fetching data, subscribing to events, or updating external resources, and keep them in sync with the rest of your application.