useEffect
is a Hook in React that allows you to run some code after rendering has completed. This is useful for scenarios where you need to perform side effects, such as making an API call or updating the title of a document, after a component has been updated
Here’s an example of how useEffect
can be used to fetch data from an API and update the state when the component is rendered
1 2 3 4 5 6 7 8 9 10 11 12 13 |
import React, { useState, useEffect } from 'react'; const ExampleComponent = () => { const [data, setData] = useState(null); useEffect(() => { fetch('https://api.example.com/data') .then(response => response.json()) .then(data => setData(data)); }, []); return <div>{data ? `Received data: ${data}` : 'Loading...'}</div>; }; |
In this example, useEffect
is being used to fetch data from an API when the component is first rendered. The second argument to useEffect
is an array of dependencies, which is used to determine when the effect should run. In this case, an empty array is passed, which means that the effect will only run once, when the component is first mounted. If you need to re-run the effect when certain props or state values change, you can include them in the array of dependencies.