
The useEffect hook is a fundamental part of React, allowing you to perform side effects in functional components. Here’s a detailed breakdown:
What is useEffect?
- The useEffect hook lets you perform side effects in your components, such as data fetching, subscriptions, or manually changing the DOM.
- It can be considered a combination of the lifecycle methods componentDidMount, componentDidUpdate, and componentWillUnmount.
Syntax
1 2 3 4 5 6 7 | useEffect(() => {
return () => {
};
}, [dependencies]);
|
登入後複製
Parameters
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).
Usage Examples
-
Basic Example: Fetching data on mount
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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));
}, []);
return <div>{data ? JSON.stringify(data) : 'Loading...' }</div>;
};
|
登入後複製
-
Cleanup Example: Subscribing to an event
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | import React, { useEffect } from 'react' ;
const EventListenerComponent = () => {
useEffect(() => {
const handleResize = () => {
console.log( 'Window resized:' , window.innerWidth);
};
window.addEventListener( 'resize' , handleResize);
return () => {
window.removeEventListener( 'resize' , handleResize);
};
}, []);
return <div>Resize the window and check the console.</div>;
};
|
登入後複製
-
Dependency Example: Running an effect based on a prop change
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | import React, { useEffect, useState } from 'react' ;
const TimerComponent = ({ delay }) => {
const [ count , setCount] = useState(0);
useEffect(() => {
const timer = setInterval(() => {
setCount(prevCount => prevCount + 1);
}, delay);
return () => clearInterval(timer);
}, [delay]);
return <div> Count : { count }</div>;
};
|
登入後複製
Best Practices
-
Specify Dependencies: Always include the variables that your effect depends on in the dependencies array to avoid stale closures.
-
Avoid Side Effects in Rendering: Keep side effects out of the render phase; use useEffect instead.
-
Use Cleanup Functions: If your effect creates subscriptions or timers, always return a cleanup function to avoid memory leaks.
Conclusion
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中文網其他相關文章!