The useEffect hook is a fundamental part of React, allowing you to perform side effects in functional components. Here’s a detailed breakdown:
useEffect(() => { // Your side effect code here return () => { // Cleanup code (optional) }; }, [dependencies]);
Effect Function: The first argument is a function that contains the side effect code. This function will run after the render is committed to the screen.
Cleanup Function (optional): The effect function can return a cleanup function that React will call when the component unmounts or before the effect runs again. This is useful for cleaning up subscriptions or timers.
Dependencies Array: The second argument is an array of dependencies. The effect runs only when one of the dependencies changes. If you pass an empty array ([]), the effect runs only once after the initial render (like componentDidMount).
import React, { useEffect, useState } from 'react'; const DataFetchingComponent = () => { const [data, setData] = useState(null); useEffect(() => { fetch('https://api.example.com/data') .then(response => response.json()) .then(data => setData(data)) .catch(error => console.error('Error fetching data:', error)); }, []); // Runs only once after the initial render return <div>{data ? JSON.stringify(data) : 'Loading...'}</div>; };
import React, { useEffect } from 'react'; const EventListenerComponent = () => { useEffect(() => { const handleResize = () => { console.log('Window resized:', window.innerWidth); }; window.addEventListener('resize', handleResize); // Cleanup function to remove the event listener return () => { window.removeEventListener('resize', handleResize); }; }, []); // Runs only once after the initial render return <div>Resize the window and check the console.</div>; };
import React, { useEffect, useState } from 'react'; const TimerComponent = ({ delay }) => { const [count, setCount] = useState(0); useEffect(() => { const timer = setInterval(() => { setCount(prevCount => prevCount + 1); }, delay); // Cleanup function to clear the timer return () => clearInterval(timer); }, [delay]); // Runs every time `delay` changes return <div>Count: {count}</div>; };
The useEffect hook is a powerful tool for handling side effects in functional components, making it essential for modern React development. By understanding its syntax and best practices, you can effectively manage component behavior and side effects.
위 내용은 useEffect 후크 설명의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!