show me useeffect example with dependency array
- User
show me useeffect example with dependency array
- Assistant
Here's an example of the useEffect hook with a dependency array:
import React, { useState, useEffect } from 'react'; function ExampleComponent() { const [count, setCount] = useState(0); const [data, setData] = useState([]); useEffect(() => { // This effect will only run when the count state changes fetch(`https://jsonplaceholder.typicode.com/posts?userId=${count}`) .then(response => response.json()) .then(data => setData(data)) .catch(error => console.log(error)); }, [count]); return ( <div> <p>Count: {count}</p> <button onClick={() => setCount(count + 1)}>Increment Count</button> <ul> {data.map(post => ( <li key={post.id}>{post.title}</li> ))} </ul> </div> ); } export default ExampleComponent;In this example, the useEffect hook has a dependency array that includes the
countstate. This means that the effect will only run when thecountstate changes.Inside the effect, we're fetching data from an API based on the current value of the state. When the data is returned, we update the state with the new results.